function log(msg) {
    if (window.console) {
        console.log("%s: %o", msg, this);
    }
}
function confirmCancel(msg) {
   return confirm(msg);
}
// These defaults should be changed the way it best fits your site
var _POPUP_FEATURES = 'location=0,statusbar=0,menubar=0,width=100,height=100';
function raw_popup(url, target, features) {
    // pops up a window containing url optionally named target, optionally having features
    if (isUndefined(features)) features = _POPUP_FEATURES;
    if (isUndefined(target  )) target   = '_blank';
    var theWindow = window.open(url, target, features);
    theWindow.focus();
    return theWindow;
}
function link_popup(src, features) {
    // to be used in an html event handler as in: <a href="..." onclick="link_popup(this,...)" ...
    // pops up a window grabbing the url from the event source's href
    return raw_popup(src.getAttribute('href'), src.getAttribute('target') || '_blank', features);
}
function form_popup(src, features) {
    // pops up a window grabbing the url from the event source's action and making a get string with the form elements
    var getString = ""
    
    for(i=0; i<src.elements.length; i++)
    {                    
        if(src.elements[i].type == "text" || src.elements[i].type == "hidden" || src.elements[i].type == "textarea" || src.elements[i].type == "button")
        {   
            getString += src.elements[i].name + "=" + src.elements[i].value + "&";
        }
        else if(src.elements[i].type == "checkbox")
        {
            alert("úbs óútfært");
            //getString += "Element Checked? " + src.elements[i].checked + "\n"
        }
        else if(src.elements[i].type == "select-one")
        {
            alert("úbs óútfært");
           //getString += "Selected Option's Text: " + src.elements[i].options[src.elements[i].selectedIndex].text + "\n"
        }
    }   
    return raw_popup(src.getAttribute('action') + "?" + getString , src.getAttribute('target') || '_blank', features);
}
function event_popup(e) {
    // to be passed as an event listener
    // pops up a window grabbing the url from the event source's href
    link_popup(e.currentTarget);
    e.preventDefault();
}
function event_popup_features(features) {
    // generates an event listener similar to event_popup, but allowing window features
    return function(e) { link_popup(e.currentTarget, features); e.preventDefault() }
}
var size = new Array(2); 
var sizeclass = new Array(2);
var acc = "Main";
size[0] = "62.5%"; sizeclass[0] = "smallfont";
size[1] = "69%"; sizeclass[1] = "largefont";

function small() {
	textSizer(0);
}
function large() {
	textSizer(1);
}
function access() {
	if(acc == "Main") acc = "Access";
	else acc = "Main";
	changeAccess();
}
function changeAccess() {
	createCookie("TextA",acc,0);
	setStyleSheet(acc);
}
function setStyleSheet(theme) {
    $('link[rel*=style]').each(function(i) {
        if ($(this).attr('title')) {
            this.disabled = true;
            if ($(this).attr('title') == theme) {
                this.disabled = false;
            }
        }
    });
//    for (i = 0; i < document.styleSheets.length; i++) {
//        if (document.styleSheets[i].title) {
//            document.styleSheets[i].disabled = true;
//            if (document.styleSheets[i].title == theme)
//                document.styleSheets[i].disabled = false;
//        }
//    }
}
function textSizer(nr) {
	var body = document.getElementsByTagName("body")[0];
	body.style.fontSize = size[nr];
	createCookie("TextSize",nr,0);
	for(i = 0;i<size.length;i++){
		if(document.getElementById(sizeclass[i])){
			if (i != nr)
				document.getElementById(sizeclass[i]).className = "";
			else
				document.getElementById(sizeclass[i]).className = "fontsel";
		}
	}
}
function rp() {
	nr = readCookie("TextSize");
	acc = readCookie("TextA");
	if(acc != null)
		changeAccess();
	else
		acc = "Main";
	if (nr != null)
		textSizer(nr);
}
function isUndefined(v) {
    var undef;
    return v===undef;
}
function onlyNumbers(el) {
    el.value = el.value.replace(/[^\+0-9]/g, "");
}
function inArray(itemId, arrObject) {
    for (var i = 0; i < arrObject.length; i++) {
        if (arrObject[i]) {
            if (arrObject[i][0] == itemId) return true;
        }
    }
    return false;
}
function compareText(a, b) {
    return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
}
function sortSections(oSelect) {
    var aOptions = new Array(oSelect.options.length);
    for (var i = 0; i < aOptions.length; i++)
        aOptions[i] = new Option(oSelect.options[i].text, oSelect.options[i].value);
    aOptions.sort(compareText);
    oSelect.options.length = 0;
    for (var i = 0; i < aOptions.length; i++)
        oSelect.options[i] = aOptions[i];
    oSelect.options[0].text = sBestAvailableText;
    oSelect.options[0].value = -1;
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else var expires = "";
	var ck = name+"="+value+expires+"; path=/";
	document.cookie = ck;
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i<ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name){createCookie(name,"",-1);}
function ds(frm) {
  var f=$(frm);
  if($("input", f).val()!="" && $("input", f).val().length > 1)
		f.submit();
  else
  	tb_show("", "/Views/ThickBoxes/Alert.aspx?id=1&KeepThis=true&TB_iframe=true&height=108&width=410&modal=true", false);
}
function omar(e, bid) {
  var bt = $(bid);
  if (typeof bt=="object") { 
    if (e.keyCode == 13) { 
      bt.click(); 
      return false; 
    } 
  }
}
function ca(){
	self.parent.tb_remove();
}
function car(){
	ca();
	self.parent.document.location.href = self.parent.document.location.href;
}
function newsletter(frm){
    var f=$(frm);
  if(isValidEmail($("#tboEmail", f).val()))
		f.submit();
  else
  	tb_show("", "/Views/ThickBoxes/Alert.aspx?id=3&KeepThis=true&TB_iframe=true&height=108&width=410&modal=true", false);
}
function changeTab(tab, content) {
  if(tab != gtab && content != gcontent) {
    $("#" + gtab).removeClass("active");
    $("#" + tab).addClass("active");
    $("#" + gcontent).hide();
    $("#" + content).show();
    gtab = tab;
    gcontent = content;
  }
}
function showImage(elm){
	$(elm).show();
}
function selectDate(id){
	var ed = id.replace("ed", "");
	$("#r" + ed).attr("checked", "checked"); 
	
	var list = $("#eventtable");
	if(list){
		 $("tbody tr", list).each(function(){
		 		$(this).removeClass("selected");
		 });
		 $("#ed" + ed).addClass("selected");
	}
}
function resetFrmEdpsParams(){
    $(G_tboTicketTypesID).val('');
    $(G_tboNoTicketsID).val('0');
    $(G_tboPriceZoneID).val('-1');
    $(G_tboSectionID).val('-1');                                                        
}
function selDate(id, s) 
{
    currSelDate = id;
    resetFrmEdpsParams();
    if (G_ajax_active == 0) 
    {  
        var ed = id.replace("ed", "");

        if (ed != "0") {
            $("#ticket-control").hide();
            $("#manual-seats-control").hide();
            $("#no-ticket").hide();
            //Loading gif
            $("#ajax-work").show();
            $(G_tboEventDateID).val(ed);
            
            switch(viewmode) {
                case 0:
                case 1:
                    $("#r" + ed).attr("checked", "checked");
                    var list = $("#eventtable");
                    if (list) { // This check isn't really valid because $ always returns an object in jquery!!
                        $("tbody tr", list).each(function() {
                            $(this).removeClass("selected2");
                        });
                        $("#ed" + ed).addClass("selected2");
                    }
                    break;
                case 2:
                    break;
                case 3:
                    $("tbody tr td", $("#timetable")).each(function() {
                        $(this).removeClass("selected");
                    });
                    $("#ed" + ed).addClass("selected");
                    break;       
            }
            
            G_ajax_active = 1;
            document.body.style.cursor = 'wait';
            var ap = $(G_tboAltPageID).val();
            loadTicketControl(ed, s, ap);
        }
        else {
            $("#ajax-work").hide();
        }
	}
}
function selectDelivery(id){
	var d = id.replace("d", "");
	$("#r" + d).attr("checked", "checked"); 
	
	$(G_tboFeeSetStructure).val(d);
	
	var list = $("#deliverytable");
	if(list.length != 0){
		 $("tbody tr", list).each(function(){
		 		$(this).removeClass("selected");
		 });
		 $("#d" + d).addClass("selected");
	}
}
function selectDeliveryAddress(id){
	var d = id.replace("d", "");
	$("#r" + d).attr("checked", "checked"); 			
	$(G_tboDelId).val(d);
	var list = $("#deliverytable");
	if(list){
		 $("tbody tr", list).each(function(){
		 		$(this).removeClass("selected");
		 });
		 $("#d" + d).addClass("selected");
	}
}

function selectDeliveryDetails(id){
	var a = id.replace("a", "");
	$("#r" + a).attr("checked", "checked"); 
	
	var list = $("#deliverytable");
	if(list){
		 $("tbody tr", list).each(function(){
		 		$(this).removeClass("selected");
		 });
		 $("#a" + a).addClass("selected");
	}
}
function goITicket(){
	var list = $("#eventtable");
	var ed = 0;
	var lng = $("#lng").val();
	if(list){
		$("tbody tr td input", list).each(function(){
			if($(this).attr("checked")==true) {
				ed = $(this).attr("id").replace("r", "");
			}
		});
		if(ed!=0){
			var url = "/Workers/Redirector.ashx?id=" + ed + "&lng=" + lng + "&i=1";
			document.location.href=url;
		} else {
			tb_show("", "/Views/ThickBoxes/Alert.aspx?id=2&KeepThis=true&TB_iframe=true&height=108&width=410&modal=true", false);
		}
	}
}
function clearRadio(){
	var list = $("#eventtable");
	if(list){
		$("tbody tr td input", list).each(function(){
			$(this).attr("checked",false);
		});
	}
}
function clearDelivery(){
	var list = $("#deliverytable");
	$(G_tboFeeSetStructure).val(0);
	if(list){
		$("tbody tr td input", list).each(function(){
			$(this).attr("checked",false);
		});
	}
}
function customRange(input) { 
  return {minDate: (input.id == 'to' ? $('#fr').datepicker('getDate') : null), 
      maxDate: (input.id == 'fr' ? $('#to').datepicker('getDate') : null)}; 
}
function isValidEmail(email) {
    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    return filter.test(email);
}
function createRow(ticketTypeId, ticketTypeName, priceSet, index, length, minTickets, maxTickets) {
    var sClass = (index%2==0) ? "even" : "odd";     

    // Create the row
    var oRow = priceSet.insertRow(index + 1);
    //create ticket selector
    makeTicketSelect(minTickets, maxTickets, index, length);
    //Add the tickettype as id for tablerow
    oRow.setAttribute("id",ticketTypeId);
    oRow.setAttribute("class",sClass); 
    oCell = oRow.insertCell(0); oCell.innerHTML = "<strong>" + ticketTypeName + "</strong>"; $(oCell).attr("class", "text");
    oCell = oRow.insertCell(1); oCell.innerHTML = sTicketSelect;
    oCell = oRow.insertCell(2); oCell.innerHTML = "<select class=\"tixpricezone\" id=\"selPriceZone-" + ticketTypeId + "\" onchange=\"selPriceZone(" + ticketTypeId + ", this.value)\"><option value=\"-1\">" + sBestAvailableText + "</option></select>";
    oCell = oRow.insertCell(3); oCell.innerHTML = "<select class=\"tixsection\" id=\"selSection-" + ticketTypeId + "\" onchange=\"selPriceSection(this.value)\"><option value=\"-1\"></option></select>";
}
function getPriceZone(priceZoneId) {
    for (var i = 0; i < aPriceZones.length; i++) {
        if (priceZoneId == aPriceZones[i][0]) return aPriceZones[i][1] + " (" + aPriceZones[i][2] + ")";
    }
}
function getSection(sectionId) {
    var soldOut = "";
    for (var i = 0; i < aSections.length; i++) {
        if (sectionId == aSections[i][0]) {
            if (aSections[i][2] == 0) soldOut = " (" + sSoldoutText + ")"; 
            return aSections[i][1] + soldOut;
        }    
    }
}
function isSectionNumbered(sectionId) {
    for (var i = 0; i < aSections.length; i++) {
        if (sectionId == aSections[i][0]) {
            return aSections[i][3];
        }    
    }
    return 1;
}
function calculateTicket(val) {
    var noItems = 0;
    var strTypes = "";
    $("#edps tr td select.notixsel").each(function (i) 
    {
        var sub = parseInt($(this).val());
        noItems = noItems + sub;         
        var tmpType = $(this).parent("td").parent("tr").attr("id");                   
                    
        for (var i = 0; i < sub; i++)
        {            
            strTypes += (strTypes.length > 0) ?  "|" + tmpType : tmpType ;
        }                  
    });    
    
    if(noItems > iMaxTickets){
        tb_show("", "/Views/ThickBoxes/Alert.aspx?id=6&KeepThis=true&TB_iframe=true&height=108&width=410&modal=true", false);
    } else {
        $(G_tboNoTicketsID).val(noItems);
        $(G_tboTicketTypesID).val(strTypes);
    }
}
function selPriceSection(sectionId) { 
    $(G_tboSectionID).val(sectionId);
    var strTypes = "";
    $("#edps tr td select.tixsection option").each(function (i) 
    {
         var val = parseInt($(this).val());         
         var numb = parseInt(sectionId);         
         if(val == numb)
         {
            this.selected = true;            
         }
      });             
}
function selPriceZone(ticketTypeId, priceZoneId) {
    
    //Get all sections....
    $("#edps tr td select.tixsection").each(function (i) 
    {
        var val = $(this).val();
        var sji = this;                                               
        // Clear the section option
        var oSection = this;
        oSection.options.length = 0;
        oSection.options[0] = new Option("", -1);   

        // Loop through the price sets and change the sections
        for (var i = 0; i < aPriceSets.length; i++) {

            // Check if ticket type and price zone match
            if (ticketTypeId == aPriceSets[i][0] && (priceZoneId == aPriceSets[i][1] || priceZoneId == -1)) {
                var bExists = false;
                for (var x = 0; x < oSection.options.length; x++)
                    if (oSection.options[x].value == aPriceSets[i][2]) bExists = true;
                if (!bExists) {
                    oSection.options[oSection.options.length] = new Option(getSection(aPriceSets[i][2]), aPriceSets[i][2]);
                }
            }
        }
        //set right pricesection
         selPriceSection(oSection.options[0].value);
        // Sort the value
        sortSections(oSection)
    
    }); 
    
    //Set the priceZone value right
    setPriceZoneValue(priceZoneId)
}

function setPriceZoneValue(priceZoneId) {   
    $(G_tboPriceZoneID).val(priceZoneId);    
    var noItems = 0;
    var strTypes = "";
    $("#edps tr td select.tixpricezone option").each(function (i) 
    {
         var val = parseInt($(this).val());         
         var numb = parseInt(priceZoneId);         
         if(val == numb)
         {
            this.selected = true;            
         }
      });    
}
function formatCurrency(strValue) {
    if (!strValue) return "";
    strValue = strValue.toString().replace(/\$|\,/g,'');
    dblValue = parseFloat(strValue);
    blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
    dblValue = Math.floor(dblValue*100+0.50000000001);
    intCents = dblValue%100;
    strCents = intCents.toString();
    dblValue = Math.floor(dblValue/100).toString();
    if(intCents<10)
        strCents = "0" + strCents;
    for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
        dblValue = dblValue.substring(0,dblValue.length-(4*i+3)) + '.' + dblValue.substring(dblValue.length-(4*i+3));
    return (((blnSign)?'':'-') + dblValue + ',' + strCents + ' SEK');
}
function buildTicketList(data) {
    // Build the result list of tickets
    var t = data.t;
    var eds = 0;
    oSeatIds = new Array(t.length);
    // Get the table and clear
    var oTable = document.getElementById("trl");
    $("#trl tr:not(#trlh)").remove();
    for(i=0;i<t.length;i++) {   
        var oRow = oTable.insertRow(i + 1);    
        oCell = oRow.insertCell(0); oCell.innerHTML = t[i].ttn; $(oCell).attr("class", "text");
        oCell = oRow.insertCell(1); oCell.innerHTML = t[i].sn; $(oCell).attr("class", "text");  
        oCell = oRow.insertCell(2); oCell.innerHTML = t[i].pzn; $(oCell).attr("class", "text");  
        oCell = oRow.insertCell(3); oCell.innerHTML = t[i].ra; $(oCell).attr("class", "text");  
        oCell = oRow.insertCell(4); oCell.innerHTML = t[i].sa; $(oCell).attr("class", "text");  
        oCell = oRow.insertCell(5); oCell.innerHTML = t[i].p; $(oCell).attr("class", "text price"); 
        eds = t[i].eds;
        oSeatIds[i] = t[i].id;
    }
    G_foundSectionId = eds;
    return eds;
}
/* AJAX */
function loadTicketControl(ed, s, ap) 
{   
    $.ajax({
      type: "GET",
      url: "/ajax/event/eventdateprice/",
      data: {eventDateId:ed, sourceId:s, alternativePageId:ap, rnd:Math.random()},
      dataType: "json",
      timeout: 10000,
      success: function(data){
        loadTicketControlComplete(data, ed, s);
      },
      error: function() {
        document.body.style.cursor = 'default';
        G_ajax_active = 0;
        $("#ajax-work").hide();
        alert("Det lykkedes ikke at hente billetinformationer fra systemet. Pr&#248;v venligst igen! Klik p&#229; en dato ovenfor eller tryk opdater i din browser.!");
      }
    });
}
function loadTicketControlComplete(data, ed, s) {
    // Create the ticket control from the results
    var arr = $.makeArray(data);
    var ipz = 0, itt = 0, is = 0;
    var uniquePriceZoneId = "";
    var aMinTickets = new Array();
    var aMaxTickets = new Array();
    clearArrays();

    //Send the number of seat combinations to page    
    $(G_tboNoSeatCombinations).val(arr.length); 

    if (arr.length != 0) {
        // Loop though all ticket types
        $.each(arr, function(i, item) {
            iMinTickets = item.MinQuantity;
            iMaxTickets = item.MaxQuantity;
            uniquePriceZoneId = item.TicketType.TicketTypeId + "|" + item.PriceZone.PriceZoneId;
            if (!inArray(uniquePriceZoneId, aPriceZones)) {
                aPriceZones[ipz++] = [uniquePriceZoneId, item.PriceZone.Name, item.PriceZone.Price];
            }
            if (!inArray(item.TicketType.TicketTypeId, aTicketTypes)) {
                aMinTickets[itt] = item.MinQuantity; 
                aMaxTickets[itt] = item.MaxQuantity;
                aTicketTypes[itt++] = [item.TicketType.TicketTypeId, item.TicketType.Name];
            }
            if (!inArray(item.Section.SectionId, aSections))
                aSections[is++] = [item.Section.SectionId, item.Section.Name, item.Section.Availability, item.Section.IsNumbered];
            aPriceSets[i] = [item.TicketType.TicketTypeId, item.PriceZone.PriceZoneId, item.Section.SectionId];
        });

        // Get the table and clear
        var oTable = document.getElementById("edps");
        $("#edps tr:not(#edpshead)").remove();

        // Loop through ticket types
        for (var i = 0; i < aTicketTypes.length; i++) {
            // Create the row
            bResults = true;
            createRow(aTicketTypes[i][0], aTicketTypes[i][1], oTable, i, aTicketTypes.length, aMinTickets[i], aMaxTickets[i]);

            // Get the selects
            var oPriceZone = document.getElementById("selPriceZone-" + aTicketTypes[i][0]);
            var oSection = document.getElementById("selSection-" + aTicketTypes[i][0]);
            var iPriorPriceZoneID = -1;
            var iPriorSectionID = -1;

            // Loop through the price sets to fill the selects
            for (var y = 0; y < aPriceSets.length; y++) {

                // Create a unique price zone id
                uniquePriceZoneId = aTicketTypes[i][0] + "|" + aPriceSets[y][1];

                // Create options for the price zones
                if (iPriorPriceZoneID != uniquePriceZoneId) {
                    var bExists = false;
                    for (var x = 0; x < oPriceZone.options.length; x++) {
                        if (oPriceZone.options[x].value == aPriceSets[y][1]) bExists = true;
                    }
                    if (!bExists && getPriceZone(uniquePriceZoneId)) {
                        oPriceZone.options[oPriceZone.options.length] = new Option(getPriceZone(uniquePriceZoneId), aPriceSets[y][1]);
                    }
                }
                iPriorPriceZoneID = uniquePriceZoneId;

                // Create options for the sections
                if (iPriorSectionID != aPriceSets[y][2]) {
                    var bExists = false;
                    for (var x = 0; x < oSection.options.length; x++) {
                        if (oSection.options[x].value == aPriceSets[y][2]) bExists = true;
                    }
                    if (!bExists) {
                        oSection.options[oSection.options.length] = new Option(getSection(aPriceSets[y][2]), aPriceSets[y][2]);
                    }
                }
                iPriorSectionID = aPriceSets[y][2];
            }

            // Remove potiential duplicates in sections
            sortSections(oSection);

            // If only one value then select them
            if (aTicketTypes.length == 1) {
                if (oPriceZone.options.length == 2) {
                    oPriceZone.options.selectedIndex = 1;
                    setPriceZoneValue(oPriceZone.options[1].value)
                }
                if (oSection.options.length == 2) {
                    oSection.options.selectedIndex = 1;
                    selPriceSection(oSection.options[1].value)
                }
            }
        }
        // Get the event date info
        loadEventDate(ed, s);
        
        if($("#timetable").length)
				{
				    var i = 0;
				    $('.notixsel option').each(function() {
				        if(i < 4){
				            var $this = $(this);
				            $this.remove();
				        }
				        else if(i == 4){
				            var $this = $(this);
				            $this.attr("selected", true);     
				        }       
				        i++;
				    });
				     var x = 0;
				    $('.tixsection option').each(function() {
				        if(x < 1){
				            var $this = $(this);
				            $this.remove();
				        }
				        else if(x == 1){
				            var $this = $(this);
				            $this.attr("selected", true);     
				            selPriceSection($this.val())
				        }       
				        x++;
				    });
						calculateTicket(4);
				} else {
					// Init the ticket count
        	calculateTicket(2);
				}
    }
    else {
        //Data is not setup correctly
        document.body.style.cursor = 'default';
        $("#ajax-work").hide();
        $("#no-ticket").show();
        G_ajax_active = 0;
    }
}

function makeTicketSelect(minTix, maxTix, ind, len) {
    sTicketSelect = "<select name=\"\"  class=\"notixsel\" onchange=\"calculateTicket(this.value)\">";
    var sBillet = "";
    for (var i = minTix; i <= maxTix; i++) {
        sBillet = (i == 1 || i == 0) ? "biljett" : "biljetter";

        if (i == 2 && ind == 0 && len == 1) {
            sTicketSelect += "<option selected=\"selected\" value=\"" + i + "\">" + i + " " + sBillet + "</option>";
        }
        else {
            sTicketSelect += "<option value=\"" + i + "\">" + i + " " + sBillet + "</option>";
        }
    }
    sTicketSelect += "</select>";
}

function loadEventDate(ed, s) {
    $.ajax({
      type: "GET",
      url: "/ajax/event/eventdate/",
      data: {eventDateId:ed, sourceId:s, token:"", rnd:Math.random()},
      dataType: "json",
      timeout: 10000,
      success: function(data){
        loadEventDateComplete(data);
      },
      error: function() {
        document.body.style.cursor = 'default';
        G_ajax_active = 0;
        $("#ajax-work").hide();
        alert("Det lykkedes ikke at hente event oplysninger!");
      }
    });
}
function loadEventDateComplete(data) {
    // Is the eventdate numbered
    if (data.EventDate.IsNumbered) {
        $("#btnView").click(function () {
            viewHall(data.EventDate.EventDateId);
        });
        // TODO: Fix this, if break on other pages then Date.aspx
        if(data.EventDate.ChooseSeats && !data.EventDate.SingleSeats) {
            $("#manual-seats-check").show();
            //$(G_tboChooseSeats).val(1);
        } else {
            $("#manual-seats-check").hide();
            //$(G_tboChooseSeats).val(0);
        }
        if(data.EventDate.SingleSeats) {
            $("#single-seats-check").show();
        } else {
            $("#single-seats-check").hide();
        }
        $("#btnView").show();
    } else {
        $("#btnView").hide();
    }
    document.body.style.cursor = 'default';
    $("#ajax-work").hide();
    $("#ticket-control").show();
    G_ajax_active = 0;
}
function loadVenues() 
{
    // Get selected values
    var eventTypeId = $("#sEventType option:selected").val();
    if(typeof(eventTypeId) == 'undefined')
        eventTypeId = 0;
    var locationId = $("#sLocation option:selected").val();  
    if(typeof(locationId) == 'undefined')
        locationId = 0;
    var cityId = $("#sCities option:selected").val(); 
    if(typeof(cityId) == 'undefined')
        cityId = 0;
    // Call the ajax function
    $.getJSON("/ajax/event/venues/?eventTypeId=" + eventTypeId + "&locationId=" + locationId + "&cityId=" + cityId + "&rnd=" + Math.random(), venuesComplete);
}
function venuesComplete(data) 
{
    // Clear the select box
    $("#sVenues").empty(); 
    // Append the default value   
    $("#sVenues").append(G_default_venue);
    // Loop through the json string and create options
    $.each(data, function(i, item) {
        options = "<option value=\"" + item.VenueUId + "\">" + item.Name + "</option>";
        $("#sVenues").append(options);
    });
}
function loadCities() 
{
    var locationId = $("#sLocation option:selected").val();
    // Call the ajax function
    $.getJSON("/ajax/region/cities/?locationId=" + locationId + "&rnd=" + Math.random(), citiesComplete);
}
function citiesComplete(data) 
{
    // Clear the select box
    $("#sCities").empty(); 
    // Append the default value   
    $("#sCities").append(G_default_city);
    // Loop through the json string and create options
    $.each(data.cities, function(i, item) {
        options = "<option value=\"" + item.CityId + "\">" + item.Name + "</option>";
        $("#sCities").append(options);
    });
}
function helpYou(s,l) {
    if($("input[name='rHelpMe']:checked").val()) {
        var rating = $("input[name='rHelpMe']:checked").val();
        // Call the ajax function
        $.ajax({
          type: "POST",
          url: "/ajax/site/helpyou/",
          data: "siteTreeId=" + s + "&siteTreeLogId=" + l + "&rating=" + rating + "&rnd=" + Math.random(),
          success: function(msg){
            helpYouComplete(msg);
          }
        });
    } 
}
function sendMail(w, n, e, m, t, u) 
{
     $.ajax({
          type: "GET",
          url: "/ajax/support/send/",
          data: "supportType=" + w + "&fullName=" + n + "&fromAddress=" + e + "&fromTel=" + m + "&text=" + t + "&userAgent=" + u + "&rnd=" + Math.random(),
          success: function(msg){
            sendMailComplete(msg);
          }
        });
}
function sendMailComplete(data)
{
    if(data == "Your query has been recieved, we will contact you soon." || data == "Beskeden er modtaget. Vi behandler din henvendelse indenfor 1-2 hverdage.")    
    {               
        $("#textarea").attr("disabled","disabled");
        $("#selectform").attr("disabled","disabled");
        $("#fullname").attr("disabled","disabled");
        $("#email").attr("disabled","disabled");
        $("#tel").attr("disabled","disabled");
        $("#senda_fyrirspurn").hide();          
    }    
    $("#answer").removeClass("dispNone");
    $("#supportalerttext").html(data);
} 
function sendRequest(ef0, ef1, ef2, ef3, ef4, ef5) 
{
    f1 = $("#selectform").val();
    f2 = $("#fullname").val();
    f3 = $("#email").val();
    f4 = $("#tel").val();
    f5 = $("#textarea").val();
    f6 = $("#useragent").val();
    
    $("#selectform").removeClass("missing");
    $("#fullname").removeClass("missing");
    $("#email").removeClass("missing");
    $("#tel").removeClass("missing");
    $("#textarea").removeClass("missing");
    
    if (f1 == '0' && f2 == '' && f3 == '' && f4 == '' && f5 == '') {
        alert(ef0);
         $("#selectform").addClass("missing");
         $("#fullname").addClass("missing");
         $("#email").addClass("missing");
         $("#tel").addClass("missing");
         $("#textarea").addClass("missing");
    } else if(f1 == '0') {
        alert(ef1);
        $("#selectform").addClass("missing");
    } else if(f2 == '') {
        alert(ef2);
         $("#fullname").addClass("missing");
    } else if(f3 == '') {
        alert(ef3);
        $("#email").addClass("missing"); 
    } else if(f4 == '') {
        alert(ef4);
        $("#tel").addClass("missing");  
    } else if(f5 == '') {
        alert(ef5);
        $("#textarea").addClass("missing");
    } else {
        sendMail(f1, f2, f3, f4, f5, f6);
    }
}  
function countryWUChanged() {
    loadWUZipCode($(G_tboWUZip).val());
}
function loadWUZipCode(zip) {
    if(zip.length > 2) {
        $(G_tboWUZipCodeID).val(0);
        var countryId = $(G_ddlWUCountry + " option:selected").val();
        // Call the ajax function
        $.getJSON("/ajax/region/zipcode/?zipCode=" + zip + "&countryId=" + countryId + "&rnd=" + Math.random(), zipCodeWUComplete);
    } 
}
function zipCodeWUComplete(data) {
    $(G_tboWUCity).val(data.ZipCode.CityName);
    $(G_tboWUZipCodeID).val(data.ZipCode.ZipCodeId);
}

function countryChanged() {
    loadZipCode($(G_tboZip).val());
}
function loadZipCode(zip) {
    if(zip.length > 2) {
        $(G_tboZipCodeID).val(0);
        var countryId = $(G_ddlCountry + " option:selected").val();
        // Call the ajax function
        $.getJSON("/ajax/region/zipcode/?zipCode=" + zip + "&countryId=" + countryId + "&rnd=" + Math.random(), zipCodeComplete);
    } 
}
function zipCodeComplete(data) {
    $(G_tboCity).val(data.ZipCode.CityName);
    $(G_tboZipCodeID).val(data.ZipCode.ZipCodeId);
}
function loadDelivery(t) {
    if($(G_chkSame).attr("checked")) {
        $.ajax({
          type: "GET",
          url: "/ajax/customer/delivery/",
          data: {token:decodeURIComponent(t), rnd:Math.random()},
          dataType: "json",
          timeout: 10000,
          success: function(data){
            loadDeliveryComplete(data);
          },
          error: function() {
            alert("Failed to load delivery address!");
          }
        });
    } else {
        $(G_tboName).val("");
        $(G_tboAddress1).val("");
        $(G_tboAddress2).val("");
        $(G_tboZip).val("");
        $(G_tboCity).val("");
        $(G_ddlCountry).val("1");
        $(G_tboZipCodeID).val("0");
    }
}
function loadDeliveryComplete(data) {
    $(G_tboName).val(data.DeliveryAddress.Name);
    $(G_tboAddress1).val(data.DeliveryAddress.AddressOne);
    $(G_tboAddress2).val(data.DeliveryAddress.AddressTwo);
    $(G_tboZip).val(data.DeliveryAddress.ZipCodeName);
    $(G_tboCity).val(data.DeliveryAddress.CityName);
    $(G_ddlCountry).val(data.DeliveryAddress.CountryId);
    $(G_tboZipCodeID).val(data.DeliveryAddress.ZipCodeId);
}
function calCardFee(dcgi, t, s) {
    if (dcgi > 0) {
        t = t.replace(".", ",");
        $.ajax({
          type: "GET",
          url: "/ajax/payment/calculatefee/",
          data: {cardTypeId:dcgi, total:t, sourceId:s, rnd:Math.random()},
          dataType: "json",
          timeout: 10000,
          success: function(data){
            calCardFeeComplete(data);
          },
          error: function() {
            alert("Failed to calculate fees!");
          }
        });
    } else {
        // Reset the total
        if($(G_chkSms).is(":checked")) {
            $("#sTotal").html(formatCurrency(parseFloat($(G_tboTotalDecimal).val().replace(",", "."))+iSmsFee));
        } else {
            $("#sTotal").html($(G_tboTotal).val());
        }
        $(G_tboTotalCalculatedDecimal).val($(G_tboTotalDecimal).val());
        $("#rowCardFee").hide();   
        $("#plCardFee").hide(); 
    }
}
function calCardFeeComplete(data) {
    $("#rowCardFee").show();
    $("#sCardFee").html(data.CardFee.Fee);

    if($(G_chkSms).is(":checked")) {
        $("#sTotal").html(formatCurrency(parseFloat(data.CardFee.TotalDecimal.replace(",", "."))+iSmsFee));
    } else {
        $("#sTotal").html(data.CardFee.Total);
    }

    $("#sCardFeeAdded").html(data.CardFee.Fee);
    $(G_tboTotalCalculatedDecimal).val(data.CardFee.TotalDecimal);
    $("#plCardFee").show();
}
function expandOrder(idx, t) {
    if ($("#o" + idx).is(":visible")) {
        $("#ex" + idx).removeClass("expandon");
        $("#ex" + idx).addClass("expand");
        $("#o" + idx).toggle();
    } else {
        $("#ex" + idx).removeClass("expand");
        $("#ex" + idx).addClass("expandon");
        $("#td" + idx).css("border-bottom", "1px solid #e4e4e4");
        $("#o" + idx + " .price").css("border-right", "1px solid #e4e4e4");
        if($("#tl" + idx).val()!="1") {
            loadOrder(idx, t);
        } else {
            $("#o" + idx).toggle();
        }
    }
}
function loadOrder(idx, t) {
    $.getJSON("/ajax/ticket/ordereventdate/?token=" + t + "&rnd=" + Math.random(), 
      function(data){
        orderComplete(data,idx)
      });
}
function orderComplete(data,idx) {
    if (data.Tickets.length > 0) { // Tickets found
        var oTable = $("#o" + idx + " table");
        var oRows = $("tbody tr", oTable);
        var oCells;

        $.each(data.Tickets, function(i, item) {
            oCells = oRows[i].getElementsByTagName("TD");
            $(oCells[0]).text(item.TicketTypeName);
            $(oCells[1]).text(item.SectionName);
            $(oCells[2]).text(item.PriceZoneName);
            $(oCells[3]).text((item.IsNumbered) ? item.RowAlias : "--");
            $(oCells[4]).text((item.IsNumbered) ? item.SeatAlias : "--");
            $(oCells[5]).text(item.Price);

        });

        // Add a border to the last row
        for (var i = 0; i < oCells.length; i++) {
            $(oCells[i]).css("border-bottom", "1px solid #e4e4e4");
        }
        $("#tl" + idx).val("1");
        $("#o" + idx).toggle();
    } else { // No tickets found, expired
        document.location.href = document.location.href;
    }
}
function findTickets() {
    // Search for tickets JSON
    var eventDateId = $(G_tboEventDateID).val();
    var quantity = $(G_tboNoTicketsID).val();
    var ticketTypes = $(G_tboTicketTypesID).val();
    var priceZoneId = $(G_tboPriceZoneID).val();
    var sectionId = $(G_tboSectionID).val();
    var alternativePageId = $(G_tboAltPageID).val();
    $("#seats").html("");
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/ajax/ticket/find/",
        data: { eventDateId: eventDateId, quantity: quantity, ticketTypes: ticketTypes, priceZoneId: priceZoneId, sectionId: sectionId,
            sourceId: sourceId, alternativePageId: alternativePageId, rnd: Math.random()
        },
        async: true,
        success: function(data) {
            findTicketsComplete(data, eventDateId, alternativePageId);
        },
        error: function() {
            errorHandler(1);
        }
    });
}

function findReservedTickets(orderId, sourceId, eventDateId) {
    $("#seats").html("");
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/ajax/ticket/getticketsbyorder/",
        data: { orderId: orderId, sourceId: sourceId, eventDateId: eventDateId, rnd: Math.random()
        },
        async: true,
        success: function(data) {
            findReservedTicketsComplete(data, eventDateId, -1);
        },
        error: function() {
            errorHandler(1);
        }
    });
}

function findReservedTicketsComplete(data, ed, al) {
    if (data.t) {
        // Build the ticket result list
        var eds = buildTicketList(data);
        //Before we draw the section we need to check if it belongs to a group and act accordingly
        groupSections(ed, eds, al);
        //groupSectionsComplete("0", ed, eds, al);
    } else {
        if (data.e) {
            alert(data.e[0].message);
        }
    }    
}

function findTicketsComplete(data, ed, al) {
    if (data.t) {
        // Build the ticket result list
        var eds = buildTicketList(data);
        //We need to check if the section is really numbered.
        if (isSectionNumbered(eds)) {
            //Before we draw the section we need to check if it belongs to a group and act accordingly
            groupSections(ed, eds, al);
            $("#manual-seats-control").show();
            window.scroll(0, $("#manual-seats-anchor").offset().top);

        } 
        //if not numbered we just do the normal stuff.
        else {
            $(G_tboSectionID).val(eds);
            // Hide elements
            $("#s1").toggle();
            $("#s2").toggle();
            $("#process").toggle();
            countDown(1);
        }           
    } else {
        if(data.e){
            alert(data.e[0].message);
        }
        goBack();
    }
    $("#ajax-work").hide();
}

function groupSections(ed, eds, al) {
    $.ajax({
        type: "GET",
        url: "/ajax/ticket/getsections/",
        data: { sourceId: sourceId, sectionId: eds, eventDateId: ed, rnd: Math.random() },
        dataType: "json",
        timeout: 10000,
        success: function(data) {
            groupSectionsComplete(data, ed, eds, al);
        },
        error: function() {
            errorHandler(2);
        }
    });
}

function groupSectionsComplete(data, ed, eds, al) {
    //no grouping we just draw the section.
    if (data == "0") {
        alert("");
        drawSection(ed, eds, al);
    }
    else {
        drawSectionGroup(ed, eds, al);
    }
}

function drawSectionGroup(ed, eds, al) {
    $.ajax({
        type: "GET",
        url: "/ajax/ticket/drawgrouping/",
        data: { sourceId: sourceId, sectionId: eds, eventDateId: ed, alternativePageId: al, rnd: Math.random() },
        dataType: "json",
        timeout: 10000,
        success: function(data) {
            drawSectionComplete(data);
        },
        error: function() {
            errorHandler(2);
        }
    });
}

function drawSection(ed, eds, al) {
    $.ajax({
      type: "GET",
      url: "/ajax/ticket/draw/",
      data: {sourceId:sourceId, sectionId:eds, eventDateId:ed, alternativePageId:al, rnd:Math.random()},
      dataType: "json",
      timeout: 10000,
      success: function(data) {
        drawSectionComplete(data);
      },
      error: function() {
        errorHandler(2);
      }
    });
}

function drawSectionComplete(data) {
    // Get info about section and verify if we can draw it
    var si = data.si;
    $("#section-info-name").html(si.n);
    $("#section-info-seats").html(si.t);
    
	// The array for all the area classes
	oAreas = new Array(data.a.length);

	// The array for all the price zone classes
	oPriceZones = new Array(data.p.length);

	// The array for all the seat classes
	oSeats = new Array(data.s.length);

	// Create the hall class
	var hall = new Hall(1, 1, data);

	// Write section
	$("#seats").html(hall.getHall());
	

    // Position the hall
	hall.center($("#seats"));	

    // Select seats in drawing
	markFoundSeats(oSeatIds);	
    
    // Build PriceZone list TODO: USE oPriceZone array.. has all info.
	buildPriceZones(data);
    
    //Generate section selector
	genSelSec();

}
function refreshSection(ed, eds, al) {
    $.ajax({
        type: "GET",
        url: "/ajax/ticket/getsections/",
        data: { sourceId: sourceId, sectionId: eds, eventDateId: ed, rnd: Math.random() },
        dataType: "json",
        timeout: 10000,
        success: function(data) {

            var url = "";
            //no grouping we just draw the section.
            if (data == "0") {
                url = "/ajax/ticket/draw/";
            }
            else {
                url = "/ajax/ticket/drawgrouping/";
            }

            $.ajax({
                type: "GET",
                url: url,
                data: { sourceId: sourceId, sectionId: eds, eventDateId: ed, alternativePageId: al, rnd: Math.random() },
                dataType: "json",
                timeout: 10000,
                success: function(data) {
                    refreshSectionComplete(data);
                },
                error: function() {
                    errorHandler(2);
                }
            });            
        },
        error: function() {
            errorHandler(2);
        }
    });
}
function refreshSectionComplete(data) {

	// The array for all the seat classes
	oSeats = new Array(data.s.length);

	// Create the hall class
	var hall = new Hall(1, 1, data)

	// Write section
	$("#seats").html(hall.getHall());

    // Position the hall
    hall.center($("#seats"));

    // Select seats in drawing
    markFoundSeats(oSeatIds);
}
function reserveTickets(ed, ap, t) {
    $.ajax({
      type: "POST", 
      dataType: "json",
      url: "/ajax/ticket/reserve/",
      data: {t:t, eventDateId:ed, alternativePageId:ap, sourceId:sourceId, rnd:Math.random()},
      async: true,
      success: function(data){
        reserveTicketsComplete(data);
      },
      error: function() {
        errorHandler(3);
      }
    });
}
/* END AJAX*/
var stripe = function() {
    var tables = document.getElementsByTagName("table");
    for (var x = 0; x != tables.length; x++) {
        var table = tables[x];
        if (!table) { return; }
        if (table.className == "stripe") {
            $("tbody tr", table).each(function() {
                var tr = $(this);
                tr.mouseover(function() {
                    $(this).addClass("hover");
                });
                tr.mouseout(function() {
                    $(this).removeClass("hover");
                });
            });
        }
        if(table.id=="timetable") {
            $("tbody tr td", table).each(function() {
                var td = $(this);
                td.mouseover(function() {
                    $(this).addClass("hover");
                });
                td.mouseout(function() {
                    $(this).removeClass("hover");
                });
            });
        }
                 

    }
}

function showHint()
{
    checkPassStrength($('#tboPassword').val(), $('#tboEmail').val());
    $("#pwhint").show();
}

function hideHint()
{
    $("#pwhint").hide();
}

// Check pass strength
function checkPassStrength(password, eMail) 
{
        
        // The arrow
        var sArrow = "<span class=\"hint-pointer\">&nbsp;</span>";                    
        // Check the strength
        var iStrength = passwordStrength(password, eMail);
        var sImage = (iStrength >= 2) ? "<img src=\"https://static.biljettforum.se/css/23082010/default/i/accept.png\" />" : "<img src=\"https://static.biljettforum.se/css/23082010/default/i/stop.png\" />";
        // Write out status 
        $("#pwhint").html(sImage + aPassStrength[iStrength] + sArrow);
}

function changeSettings()
{
    $("#settings-alert").hide();
        var isOk = true;            
    
    //First check. Check if any inputs are empty.
        $("#inputContainer input[type=text], #inputContainer input[type=password], #inputContainer select").each(function() {                                                  
            if($(this).val() == "" && $(this).attr("id") != "tboAddress2"  && $(this).attr("id") != "tboPassword" && $(this).attr("id") != "tboPassword2" || $(this).val() == "-1"){              
                $(this).attr("style", "border-color:#DD511E;");  
                isOk = false;                        
            }
            else
                $(this).attr("style", "");        
        });     
        if(!isOk)       
        {
            $("#alertHeader").text(aMissingInputHeader);
            $("#alertText").text(aMissingInputText);
            $("#settings-alert").show();
        }
        else
        {
            //if we are changing passwords.
            if($("#chkChangePassword").is(":checked")){
                //Next check, check if the passwords are the same.
                if($("#tboPassword").val() != $("#tboPassword2").val()){                
                    $("#tboPassword").attr("style", "border-color:#DD511E;");  
                    $("#tboPassword2").attr("style", "border-color:#DD511E;");  
                
                    $("#alertHeader").text(aPwNotMatchHeader);
                    $("#alertText").text(aPwNotMatchText);
                    $("#settings-alert").show();
                }   
                else
                {
                    //next check if the passwords are strong enough
                    if(passwordStrength($("#tboPassword").val(), $("#tboEmail").val()) < 2)
                    {           
                        $("#tboPassword").attr("style", "border-color:#DD511E;");  
                        $("#tboPassword2").attr("style", "border-color:#DD511E;");  
                    
                        $("#alertHeader").text(aPwStrengthTitle);
                        $("#alertText").text(aPwStrengthText);
                        $("#settings-alert").show();
                    }
                    else
                    {                    
                        $("#changeWebUser").submit();
                    }
                }
            }
            else{
                $("#changeWebUser").submit();
            }           
        }        
}

function settingsChangeComplete(data){

    if(data == 1) {
        $("#alertHeader").text(aMissingInputHeader);
        $("#alertText").text(aMissingInputText);
        $("#settings-alert").show();
    }
    else if (data == 2) {
        $("#alertHeader").text(aPwNotMatchHeader);
        $("#alertText").text(aPwStrengthText);
        $("#settings-alert").show();
    } 
    else if (data == 3) {
       $("#alertHeader").text(aPwStrengthTitle);
        $("#alertText").text(aPwStrengthText);
        $("#settings-alert").show();
    } 
    else if (data == 0) {
       $("#settings-alert").hide();
         window.location = "/profil/dashboard/"
    } 
}

//Got it from here http://www.reynoldsftw.com/2009/03/live-email-validation-with-jquery/
function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function isValidCpr(cpr)
{
    if (isNaN(cpr))
        return false;
    if(cpr.length == 10)
        return true;
    else return 
        false;    
}

function isValidReg(reg)
{
    if (isNaN(reg))
        return false;
    if(reg.length == 4)
        return true;
    else return 
        false;    
}


function rate() 
{    

    $("#alertBox").hide();
    var isOk = true;
    
    //First check. Check if any inputs are empty.
    $("#inputContainer input[type=text], #inputContainer input[type=password]").each(function() {
    if ($(this).val() == "" && $(this).attr("id") != "tboAddress2" && $(this).attr("id") != "tboMobile" && $(this).attr("id") != "tboPhone" && $(this).attr("id") != "recaptcha_response_field") {
            $(this).attr("style", "border-color:#DD511E;");
                isOk = false;                        
            }
        else
            $(this).attr("style", "");        
    });     
    if(!isOk)       
    {
        $("#alertHeader").text(aMissingInputHeader);
        $("#alertText").text(aMissingInputText);
        $("#alertBox").show();
    }
    else
    {
        //Lets check the email address
        if(!isValidEmailAddress($("#tboEmail").val())) {                          
            $("#tboEmail").attr("style", "border-color:#DD511E;");                  
        
            $("#alertHeader").text(aEmailTitle);
            $("#alertText").text(aEmailText);
            $("#alertBox").show(); 
        }   
        //Next check if agreement is checked.     
        else if(!$("#chkAgree").is(':checked'))                      
        {
            $("#alertHeader").text(aTermsHeader);
            $("#alertText").text(aTermsText);
            $("#alertBox").show();
        }
        //Check if we have any tickets selected                 
        else if($("#ddlTickets").val() == 0)                  
        {
            $("#ddlTickets").attr("style", "border-color:#DD511E;");          
            $("#alertHeader").text(aNoSelectedTicketsTitle);
            $("#alertText").text(aNoSelectedTicketsText);
            $("#alertBox").show();
        }
        //Is cprnumber valid  
        else if(!isValidCpr($("#tboCpr").val()))
        {
            $("#tboCpr").attr("style", "border-color:#DD511E;");   
            $("#alertHeader").text(aCprTitle);
            $("#alertText").text(aCprText);
            $("#alertBox").show();
        }    
        //Is konto number valid       
        else if(!isValidCpr($("#tboKon").val()))
        {
            $("#tboKon").attr("style", "border-color:#DD511E;");   
            $("#alertHeader").text(aKonTitle);
            $("#alertText").text(aKonText);
            $("#alertBox").show();
        }
        //Is reg number valid
        else if (!isValidReg($("#tboReg").val()))
        {
             $("#tboReg").attr("style", "border-color:#DD511E;");   
             $("#alertHeader").text(aRegTitle);
             $("#alertText").text(aRegText);
             $("#alertBox").show();
        }   
        else
        {
             var f = $("#rateForm");
             f.submit();
        }                 
                                
    }         
}

function rateComplete(data){

    if(data == 1) {
        $("#alertHeader").text(aTermsHeader);
        $("#alertText").text(aTermsText);
        $("#alertBox").show();
    }
    else if (data == 2) {
        $("#alertHeader").text(aMissingInputHeader);
        $("#alertText").text(aMissingInputText);
        $("#alertBox").show();
    } 
    else if (data == 3) {
        $("#alertHeader").text(aEmailTitle);
        $("#alertText").text(aEmailText);
        $("#alertBox").show();
    } 
    else if (data == 4) {
        $("#alertHeader").text(aCprTitle);
        $("#alertText").text(aCprText);
        $("#alertBox").show();
    }    
    else if (data == 5) {
        $("#alertHeader").text(aKonTitle);
        $("#alertText").text(aKonText);
        $("#alertBox").show();
    } 
    else if (data == 6) {
        $("#alertHeader").text(aRegTitle);
        $("#alertText").text(aRegText);
        $("#alertBox").show();
    }
    else if (data == 7) {
        $("#alertHeader").text(aNoSelectedTicketsTitle);
        $("#alertText").text(aNoSelectedTicketsText);
        $("#alertBox").show();
    }
    else if (data == 8) {
        $("#alertHeader").text(aCaptchaWrongTitle);
        $("#alertText").text(aCaptchaWrongText);
        $("#alertBox").show();
    }
    else if (data == 0) {
       $("#alertBox").hide();
    } 
} 

//Birthdaypicker code
function bDayPickerStartSettings()
{
	    //Set currentdate
		currentTime = new Date();		
		//Set currentYear        
		currentYear = currentTime.getFullYear();
		//Fill the month array
		fillMonthArray();
		//Populate years
		populateYears();
}
function populateMonthOptions(year){
	var op = "<option value=\"-1\">" + langMonth + "</option>";
	if(year.value != -1){
		for(var i=0; i<12; i++)
		{
			op = op + "<option value=\"" + i + "\">" + arrMonths[i] + "</option>";
		}			
	}	
	$("#ddlMonth").html(op);
	populateDays();
}
function populateYears(){
	var op = "<option value=\"-1\">" + langYear + "</option>";
	for(var i=currentYear; i >= 1900; i--)
	{
		op = op + "<option value=\"" + i + "\">" + i + "</option>";
	}	
	$("#ddlYear").html(op);
}
function populateDays(){
	var year = $("#ddlYear").val();
	var month = $("#ddlMonth").val();
	var day = 1;
	var op = "<option value=\"-1\">" + langDay + "</option>";		
	if(month != -1 && year != -1) {
		var selectedTime = (new Date(year, month, day))
		var numberOfDaysInMonth = getMonthDays(selectedTime);
		for(var i=1; i <= numberOfDaysInMonth; i++) {
			op = op + "<option value=\"" + i + "\">" + i + "</option>";
		}
	}
	$("#ddlDay").html(op);
}
function getMonthDays(dt) {
    var this1st = (new Date(dt.getFullYear(), dt.getMonth(), 1)).getTime();
    var next1st = (new Date(dt.getFullYear(), dt.getMonth() + 1, 1)).getTime();
    return Math.floor((next1st - this1st) / 86400000);
}
function countTimeout(s) {
    var secs = parseInt(s);
    if (secs >= 0) {
        $("#active-basket li a,.ticket-box-content p strong span").text(secondstotime(secs));
        window.setTimeout('countTimeout('+(s-1)+')',1000);
    }
}
function secondstotime(secs) {
    var t = new Date(1970,0,1);
    t.setSeconds(secs);
    var s = t.toTimeString().substr(3,5);
    if(secs > 86399)
        s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    return s;
}
function orderUpdated(price) {
    $("#order-update p.total span").html(price);
    $("#order-update").slideDown("fast", function() {
        setTimeout("$('#order-update').slideUp('fast');",5000);
    });
}
