var Global = {};
var eventXML = null;
var eventDateArray = [];
var tempEventDateArray = [];
var eventCategory;
var calDates_todaysDate = new Date();
var buildDateArray = [];
var grabbedLabel;
var timeLabel;
var dropDownList = [];
var otherViews = [];
var unsortedEvents = new Array();
var unsortedEventImages = new Array();
var allEents;
var urlFilter = false;
var passNames = [];


function getEventDates(){
	$.get("/xml/events/"+propCode+".xml",{},function(feedx){
		$.get("/xml/events_onsale/"+propCode+".xml",{},function(feedb){				
			$("event", feedb).each(function(){
				$("event eventID:contains('"+$(this).find('eventID').text()+"')", feedx).length==0?$(feedx).find('harrahs').append($($(this))):"";
			});
			eventXML = feedx;
			buildEventDateXML();
		}).error(function() {
			eventXML = feedx;
			buildEventDateXML(); 
		});
	});
}


function buildEventDateXML(){	
	if(checkIfValid(window.eventID)){
		addEventCal("#datepicker",eventID,"#EventModule-Date");
	}else if(!checkIfValid(window.allStagePage)){
		if(checkIfValid(window.showFilter)){
			$("#PropertyModule-Search").show();
			$("#PropertyModule-Venues .contentArea").css("height",$("#PropertyModule-content").height()-$("#PropertyModule-Search").height()-10);
			if($("#PropertyModule-Venues .VenueModule").length == 0){
				$("#PropertyModule-Venues .contentArea img").css("margin-top",($("#PropertyModule-content").height()-$("#PropertyModule-Search").height()-10 - $("#PropertyModule-Venues .contentArea img").height())/2);
			}
		}else{
			$("#PropertyModule-Search").remove();
			$("#PropertyModule-Venues .contentArea").css("height",$("#PropertyModule-content").height());
			if($("#PropertyModule-Venues .VenueModule").length == 0){
				$("#PropertyModule-Venues .contentArea img").css("margin-top",($("#PropertyModule-content").height() - $("#PropertyModule-Venues .contentArea img").height())/2);
			}
			
		}
		checkURLString();
		
		$("#PropertyModule-Venues").show();
		loadEvents();
	}else if(checkIfValid(window.allStagePage)){
	
			$.get("/xml/events/allStagePassEvents.xml",function(pass){
				$('allStageEvent',pass).each(function(){
					passNames.push($(this).text());
				});
				buildEventOverlay(passNames);
			});
	}
}



function checkURLString(){
	buildCatagoryList();
	if((checkIfValid($.url.decode($.getUrlVar('eventFilter'))) && $.url.decode($.getUrlVar('eventFilter')) in Global.oc(dropDownList)) && $.url.decode($.getUrlVar('eventFilter')) !== "ALL"){
		catagoryList = [];
		catagoryList.push($.url.decode($.getUrlVar('eventFilter')));
	}else if(((catagoryList.length==0)&& checkIfValid(window.enableFilter)) || (checkIfValid($.url.decode($.getUrlVar('eventFilter'))) && ($.url.decode($.getUrlVar('eventFilter')) == "ALL"))){
		addAllCatagories();
	}
	if(checkIfValid($.getUrlVar('eventFilter'))){
		urlFilter = true;
	}
	
	if(catagoryList.length==1){
		$("#catagoryList").val(catagoryList[0]);
	}
}

function buildCatagoryList(){
	$('event', eventXML).each(function(i){
		if((!($(this).find("category").text() in Global.oc(dropDownList))) && (checkIfValid(catagoryList)?($(this).find("category").text() in Global.oc(catagoryList)):true)){
			dropDownList.push($(this).find("category").text());
		}
	});

	for(x in catagoryList){		
		if(!(catagoryList[x] in Global.oc(dropDownList))){
			catagoryList.splice(x,1);
		}
	}

	catagoryList.sort();
	dropDownList.sort();
	for (i in dropDownList){
		$("#catagoryList").append("<option value='"+dropDownList[i]+"'>"+dropDownList[i]+"</option>");	
	}

	$("#catagoryList").change(function (){
		if($(this).val() !== "ALL"){
			catagoryList = [$(this).val()];
		}else{
			addAllCatagories();
		}
		window.location.href = window.location.href.split("?")[0]+"?"+$.param({eventFilter:$(this).val()});
	});
}

function addAllCatagories(){
	catagoryList = [];
	for (i in dropDownList){
		catagoryList.push(dropDownList[i]);
	}
	
}

function addCalRollovers(){
	$('.viewDates').bind({
	  mousedown: function() {
	  	if($(this).parent().find(".viewDateCal").html() == ""){
	    	addEventCal($(this).find(".viewDateCal"),$(this).find("a").attr("rel"),null);
	    }else{
	    	$(this).parent().find(".viewDateCal").show("fast");
	    }
	  },
	  mouseleave: function() {
	     $(this).parent().find(".viewDateCal").hide("fast");
	  }
	});
}


function buildEventDateArray(ID){
	eventDateArray = [];
	$('event', eventXML).each(function(){
		if(($(this).find("eventID").text() == ID) || ($(this).find("eventTitle").text().toLowerCase().indexOf(ID.toLowerCase()) != -1)){
			$(this).find("showing").each(function(){
				eventDateArray.push(new Date($(this).find('eventDate').text().split("-").join("/")));	
			});	
			eventCategory = $(this).find("category").text();

			if(eventCategory !== "Concerts & Shows"){
				$("#EventModule-SearchLinks a:eq(1)").html("VIEW MORE EVENTS");
				//TWS - updated Start Time text to update just the label text - was replacing the text and time
				$("#eventmodule-time-label").html("START TIME:");
				$("#socialLinks .moduleHeader").html("Share this Event");
				$("#EventModule-TicketInfo>div:eq(0)>div:eq(1)>div:eq(1)").html("Upcoming Dates");
				if($(this).find('reservationLink').length<0){
					$("#EventModule-TicketInfo>div:eq(1)").remove();
				}
			}
				grabbedLabel = $("#eventmodule-time-label");
				timeLabel = grabbedLabel.html()!==null?grabbedLabel.html():"SHOW TIME: ";
		}
	});
	
	if(eventDateArray.length!=0){
		return eventDateArray;
	}else{
		return null;
	}
}

function addEventCal(DIV,ID,DISPLAYID){
	buildDateArray = buildEventDateArray(ID);
	if(buildDateArray){
		$(DIV).html("");
		$("#datepicker").css("border", 0);
		$(DIV).datepicker("destroy");
		$(DIV).datepicker({dayNamesMin:['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],hideIfNoPrevNext: true,minDate: buildDateArray[0],maxDate: buildDateArray[buildDateArray.length-1], prevText: '&#171;', nextText: '&#187;', numberOfMonths:1, eventDates:buildDateArray, onSelect: function(dateText, inst) {
				if(checkIfValid(window.eventID)){
					$(DISPLAYID).html(new Date(dateText).format('l, F d, Y'));
					$('event', eventXML).each(function(){
						if($(this).find("eventID").text() == ID){
							$(this).find("showing").each(function(){
								if(dateText == $(this).find("eventDate").text().split("-")[1]+"/"+$(this).find("eventDate").text().split("-")[2]+"/"+$(this).find("eventDate").text().split("-")[0]){
									$("#EventModule-Time").html("<span id='eventmodule-time-label'>"+ timeLabel+"</span> "+convertTime($(this).find("startTimes").text()))
								}
							});
						}
					});				
				}
			}
		});
		if(DISPLAYID){
			$(DISPLAYID).html(buildDateArray[0].format('l, F d, Y'));
			$('event', eventXML).each(function(){
				if($(this).find("eventID").text() == ID){
					var grabbedLabel = $("#eventmodule-time-label");
					$("#EventModule-Time").html("<span id='eventmodule-time-label'>"+ timeLabel+"</span> "+convertTime($(this).find("showing:first startTimes").text()))
				}
			});
		}
	}else{
		$(DIV).find('#loadingCopy').html("Please check back later for show dates.");
	}
}

function pageselectCallback(page_index, jq){
    var new_content = $('#hiddenresult div.result:eq('+page_index+')').clone();
    $('#specialGuestSearchresult').empty().append(new_content);
    addCalRollovers();
    return false;
}
function initPagination(section) {
    // count entries inside the hidden content
    var num_entries = jQuery('#hiddenresult div.result').length;
    // Create content inside pagination element
    $(section+">.paginationClass").pagination(num_entries, {
        callback: pageselectCallback,
        items_per_page:1 // Show only one item per page
    });
     $(section+">.paginationClass").trigger('setPage', [0]);
     
     if($(section+">.paginationClass .pagination a").length == 0){
     	$(section+">.paginationClass .pagination").css("display","none");
     }
}

function buildLabelList(){
	allEents = "";
	
	if((((catagoryList.length >= 1) && (!checkIfValid(window.residentArtist))) || checkIfValid(urlFilter)) && checkIfValid(window.enableFilter))
	{
		unsortedEvents.sort(sortByType);
		for(i in catagoryList){
			var holderTemplate = getTemplate("eventHolder_Template");
				holderTemplate = holderTemplate.replace(/#eventHolderID#/gi, catagoryList[i].split(" ")[0]);
				holderTemplate = holderTemplate.replace(/#eventHolderHeader#/gi, catagoryList[i]);
				holderTemplate = holderTemplate.replace(/#eventHolderContent#/gi, "#"+catagoryList[i]+"#");
				allEents += holderTemplate;			
			}
			$("#regMainContent").append(allEents);
	}else if(!checkIfValid(window.residentArtist) && !checkIfValid(window.showFilter) && !checkIfValid(urlFilter)){
	 
		otherViews.push(upcomingEventsModuleHeader);
		
		for(i in otherViews){
			var holderTemplate = getTemplate("eventHolder_Template");
				holderTemplate = holderTemplate.replace(/#eventHolderID#/gi, otherViews[i].split(" ")[0]);
				holderTemplate = holderTemplate.replace(/#eventHolderHeader#/gi, otherViews[i]);
				holderTemplate = holderTemplate.replace(/#eventHolderContent#/gi, "#"+otherViews[i]+"#");
				allEents += holderTemplate;			
			}
			$("#regMainContent").append(allEents);
	}else if(checkIfValid(residentArtist) && !checkIfValid(window.showFilter)){
		
		otherViews.push(residentArtistModuleHeader,otherArtistModuleHeader);
		
		for(i in otherViews){
			var holderTemplate = getTemplate("eventHolder_Template");
				holderTemplate = holderTemplate.replace(/#eventHolderID#/gi, otherViews[i].split(" ")[0]);
				holderTemplate = holderTemplate.replace(/#eventHolderHeader#/gi, otherViews[i]);
				holderTemplate = holderTemplate.replace(/#eventHolderContent#/gi, "#"+otherViews[i]+"#");
				allEents += holderTemplate;			
			}
			$("#regMainContent").append(allEents);	
	}
}


function loadEvents(){
	$(".resultsDisplay").remove();
	
	var eventBuildNumber = 0;
	var maxPerPage = checkIfValid(window.eventsPerPage)?window.eventsPerPage:50;
	var tempEventBuild = '';
	$(".results").html('');
	unsortedEvents = [];
	unsortedEventImages = [];
	$('#hiddenresult').html('');
	if(checkIfValid(window.rotatingHeader)){
		$("#pageHero").html('');
	}
	var x;
	$('event', eventXML).each(function()
	{
			var rawDate = $(this).find("showing:first eventDate").text(); // returns first show date as YYYY-MM-DD
			var dateArray = rawDate.split("-"); // Must break apart because IE does not recognize this format
			var eventMonth = dateArray[1];
			var eventDay = dateArray[2];
			var eventYear = dateArray[0];
			var eventDate = new Date(eventYear, (eventMonth-1)/1, eventDay);		
		if((checkIfValid(window.venueList)?(String($(this).find("venue").text())in Global.oc(venueList)):true) && (checkIfValid(window.catagoryList)?(String($(this).find("category").text())in Global.oc(catagoryList)):true) && (eventDate>=new Date(calDates_todaysDate.getFullYear(),calDates_todaysDate.getMonth(),calDates_todaysDate.getDate())))
			{
			unsortedEvents.push({
				"eventImage":$(this).find("largeImagePath").text(),
				"eventTitle":$(this).find("eventTitle").text(),
				"eventVenue":$(this).find("venue").text(),
				"purchaseTicketsLink":$.trim($(this).find("reservationLink").text()).length>0?$(this).find("reservationLink").text():"http://www."+getDomainURL()+$(this).find("eventDetailsPageUrl").text(),
				"purchaseTicketText":$.trim($(this).find("reservationLink").text()).length>0?"Purchase Tickets":"Learn More",
				"shortDiscription":$(this).find("description").text(),
				"learnMore":$(this).find("eventDetailsPageUrl").text(),
				"showDate":eventDate,
				"showTime":$(this).find("showing:first startTimes").text(),
				"eventID":$(this).find("eventID").text(),
				"eventCategory":$(this).find("category").text(),
				"longDiscription":$(this).find("description").text(),
				"residentArtist": checkIfValid(window.residentArtist)?(($.trim(String($(this).find("eventTitle").text()))in Global.oc(residentArtist)) || Global.reverseCheck($.trim(String($(this).find("eventTitle").text())),residentArtist)):false
				});				
			}
	});

		
	
	// Sort the multi-dimensional array based on date
	unsortedEvents.sort(sortByDate);
	
	buildLabelList();
	
	// Add sorted events to the page
	for (x = 0; x < unsortedEvents.length; x++)
	{
			var template = getTemplate("eventModule_Template");
				template = template.replace(/#eventImage#/gi, unsortedEvents[x].eventImage);
				template = template.replace(/#eventName#/gi, unsortedEvents[x].eventTitle);
				template = template.replace(/#eventVenue#/gi, unsortedEvents[x].eventVenue);
				template = template.replace(/#purchaseTicketsLink#/gi, unsortedEvents[x].purchaseTicketsLink);
				template = template.replace(/#shortDiscription#/gi, unsortedEvents[x].shortDiscription);
				template = template.replace(/#learnMore#/gi, unsortedEvents[x].learnMore);
				template = template.replace(/#showDate#/gi, unsortedEvents[x].showDate.format('l, F d, Y'));				
				template = template.replace(/#showTime#/gi, (trim(unsortedEvents[x].showTime))?"@ "+convertTime(unsortedEvents[x].showTime):"");	
				template = template.replace(/#eventID#/gi, unsortedEvents[x].eventID);	
				template = template.replace(/#ticketText#/gi, unsortedEvents[x].purchaseTicketText);
								
				if((((catagoryList.length >= 1) && !checkIfValid(window.residentArtist)) || urlFilter) && checkIfValid(window.enableFilter)){
					$("#"+unsortedEvents[x].eventCategory.split(" ")[0]).append(template);
				}else if(((unsortedEvents[x].residentArtist  && !checkIfValid(window.enableFilter))) || (!checkIfValid(window.enableFilter) && !checkIfValid(window.residentArtist))){
					$("#"+otherViews[0].split(" ")[0]).append(template);
				} else {
					$("#"+otherViews[1].split(" ")[0]).append(template);
					
					/*
eventBuildNumber++
					if (eventBuildNumber < maxPerPage){
							tempEventBuild = tempEventBuild+template;
						}else{
							tempEventBuild = tempEventBuild+template;
							tempEventBuild = "<div class='result'>"+tempEventBuild+"</div>";
							eventBuildNumber = 0;
							$('#hiddenresult').append(tempEventBuild);
							tempEventBuild = '';
						}
*/
				}
			
			
			
			if(x<8 && checkIfValid(window.animateHero))
			{
				$("#pageHero").append('<li><a href="'+unsortedEvents[x].learnMore+'"><img width="430" height="242" border="0" rel="'+unsortedEvents[x].longDiscription+'" alt="'+unsortedEvents[x].eventTitle+'" src="'+unsortedEvents[x].eventImage.split("_300x225").join("_430x242")+'"/></a></li>')
			}

	}
	
	tempEventBuild = "<div class='result'>"+tempEventBuild+"</div>";
	$('#hiddenresult').append(tempEventBuild);
	addCalRollovers();
	//initPagination("#specialGuestEvents");
	
	if(checkIfValid(window.heroOrder)){
		reorderSlideShow("pageHero");
	}
	buildSlideShow("pageHero");
	addGooglePlusOne();
	addTwitterShare();
	addLikeButton('recommend');
	connectToFacebook();
}

function reorderSlideShow(slideShowDiv){
	var numberOfHeroMusts = heroOrder.length-1;
	var tempLI;
	var tempEvt;
	var tempParent;
	
	for (n=numberOfHeroMusts;n>=0;n--){
		if($("#"+slideShowDiv+" img[alt*='"+heroOrder[n]+"']").length == 1){
			tempLI = $("#"+slideShowDiv+" img[alt*='"+heroOrder[n]+"']").closest("li");
			$("#"+slideShowDiv+" img[alt*='"+heroOrder[n]+"']").closest("li").remove();
			$("#"+slideShowDiv).prepend(tempLI);
		}
		
		if($(".module_Title a:contains('"+heroOrder[n]+"')").length == 1){
			tempParent = $(".module_Title a:contains('"+heroOrder[n]+"')").closest(".residentEventModule").parent();
			tempEvt = $(".module_Title a:contains('"+heroOrder[n]+"')").closest(".residentEventModule");
			$(".module_Title a:contains('"+heroOrder[n]+"')").closest(".residentEventModule").remove();
			tempParent.prepend(tempEvt);
		}
	}
}

function buildEventOverlay(eventIDs){
	var returnEvent = '';
	for(i in eventIDs){
		$("eventTitle:contains('"+eventIDs[i]+"')", eventXML).each(function(){
			$('#allEvents_subsection_'+($('img[alt*="'+eventIDs[i]+'"]').closest('.slideHolder').attr('id').split('main')[1]-1)).append("<div class='passEventMobule eventInfo'><div class='clearfix'><div class='passEventImg'><img src='http://www.caesars.com"+$(this).closest('event').find('imagePath').text()+"'/></div><div class='passEventName'>"+$(this).closest('event').find('eventTitle').text()+"</div><div class='passEventLocation'><span>Location: </span>"+$(this).closest('event').find('propertyName').text()+"</div></div><div class='passEventDescription'>"+$(this).closest('event').find('description').text()+"</div><div class='eventCTA'><a data-icon='&#0155;' class='button' href='"+$(this).closest('event').find('eventDetailsPageUrl').text()+"'>Learn More</a></div></div>");
		//<div class='passEventTime'>"+eventTimes($(this).closest('event').find('startTimes:eq(0)').text())+"</div>
		});
	}
	$('#allEventsOverlay div .passEventMobule:last-child').addClass("last");

}

function eventTimes(Times){
	var timeReturn = "<span>Start Time"+(Times.split(',').length>1?"s:</span>":":</span>")
	for (i in Times.split(',')){
		timeReturn += " "+convertTime(Times.split(',')[i])+(i<Times.split(',').length-1?",":'');
	}
	return timeReturn;
}

function buildSlideShow(divName){
			$.getScript('/javascript_includes/2011_templates/jquery.anythingslider.js', function() {
				$('#'+divName+'').anythingSlider({
					startPanel          : 1,
					width               : 664,
					height              : 420,
					autoStart			: ($('#'+divName+' li').length > 1)?true:false,
					buildNavigation		: false,
					startText           : "",   // Start button text
					stopText            : "",   // Stop button text
					delay               : checkIfValid(window.slideShowDelay)?window.slideShowDelay:7000,
					onInitialized		: function(){checkIfValid(window.discriptionBox)?addHeroInfo($('#'+divName+' li:eq(1) img').attr('alt'), $('#'+divName+' li:eq(1) img').attr('rel')+' <br><br><a data-icon="&raquo;" href="'+$('#'+divName+' li:eq(1) a').attr('href')+'" class="button black small">learn More</a>'):"";},
					onSlideComplete		: function(){checkIfValid(window.discriptionBox)?addHeroInfo($('#'+divName+' .activePage img').attr('alt'), $('#'+divName+' .activePage img').attr('rel')+' <br><br><a data-icon="&raquo;" href="'+$('#'+divName+' .activePage a').attr('href')+'" class="button black small">learn More</a>'):"";},
					resizeContents      : false
					});	
				});
			}

function addHeroInfo(title,info){
	$(window.discriptionBox+" .moduleHeader").html(title);
	$(window.discriptionBox+" .moduleHeader").siblings().html(info);
}

function getDomainURL(){
	return location.href.match(/:\/\/(www\.)?(.[^/:]+)/)[2];
}

Global.oc = function(a,deepSearch){
  var o = {};
  for(var i=0;i<a.length;i++)
  {
  	if(deepSearch){
    	o[a[i][deepSearch]]='';
    }else{
     	o[a[i]]='';
    }
  }
  return o;
}

Global.reverseCheck = function(s,a){
  var r = {};
  for(var i=0;i<a.length;i++){
     if(s.indexOf(String(a[i])) !== -1){
      return true;
     }
  }
  return false;
}

function checkIfValid(inputVAR){
	if((inputVAR !== undefined) && (inputVAR !== "undefined") && (inputVAR !== null) && (inputVAR !== "null")){
		switch(typeof(inputVAR)){
				case "object":
				return inputVAR.length>0?true:false;
				break;
				case "string":
				return inputVAR.length>0?true:false;
				break;
				case "boolean":
				return inputVAR;
				break;
			}
	}
	return false;
}
function getTemplate(id) {
  var template;
  var div = $("#"+id).html();
  
  if (div == null)
    return "";

  // get the HTML
  template = div;
  // strip the special comment tags
  template = template.replace(/\<\!--\]|\[--\>/gi, '');
 	
  return template;
}

// sort parameters functions
function sortByDate(a, b)
{
	var e1 = a.showDate;
	var e2 = b.showDate;
	return ((e1 < e2) ? -1 : ((e1 > e2) ? 1 : 0));
}

function sortByType(a, b)
{
	var c1 = a.eventCategory;
	var c2 = b.eventCategory;
	return ((c1 < c2) ? -1 : ((c1 > c2) ? 1 : 0));
}

function to_military(val)  {            
    var pm = 0, hour = 0, min = 0;
    
    if( val.search( /PM/i ) >= 0 )
        pm = 12, val = val.replace( /PM/i, "" );
        
        
    if( val.search( /AM/i ) >= 0 )
        val = val.replace( /AM/i, "" );
        
    var vals = val.split(':');
		hour = parseInt(vals[0]);
   
    if(pm==12){
    	if(hour!==12){
    	hour = ((Number(hour)+Number(pm)));
    	}
    }
       		
    
    if( hour < 10 ) hour = "0" + hour;
    
    min = ( vals.length > 1 ) ? parseInt( vals[ 1 ] ) : 0;
    
    if( min < 10 ) min = "0" + min;
    
    return hour + ":" + min+":00";
}

function convertTime(inputTime) {
	
		// Grab the first time value and format it
		var hours = inputTime.split(':')[0];
		var minutes = inputTime.split(':')[1];
		var seconds = inputTime.split(':')[2];
	
		var timeValue = "" + ((hours >12) ? hours-12 :hours);
			timeValue += ((minutes < 10) ? ":00" : ":" + minutes);
			timeValue += ((hours >= 12) ? "PM" : "AM");
			
		// See if there's a second time value
		// It will look like this HH:MM:SS,HH:MM:SS
		if (inputTime.indexOf(",") > -1)
		{
			var hours2 = seconds.split(',')[1];
			var minutes2 = inputTime.split(':')[3];
			
			var timeValue2 = "" + ((hours2 >12) ? hours2-12 :hours2);
			timeValue2 += ((minutes2 < 10) ? ":00" : ":" + minutes2);
			timeValue2 += ((hours2 >= 12) ? "PM" : "AM");
			
			timeValue += ', ' + timeValue2;
		}
		return timeValue;

}
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

