(function($) {
	//splittext function is used to split the continous string
	function splitText(str){ 

		if(str.indexOf(" ")!=-1 || str.length <15)
			return str;
		var arr = new Array();
		arr = str.split("");
		var finalStr = "";

		for(var i=0;i<arr.length;i++){ 	
			if(i>0 && (i+1)%15 == 0)
				finalStr += arr[i] + "<br />";
			else
				finalStr += arr[i];
		}
		return finalStr;
	}
	
	//get omniture cookie info to flex
	function getCookieAllIn(name) {
		var nameEQ = name+'=';
		if (!document.cookie) { 
			return false; 
		}
		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 false;
	} 
	
	function toggleCookie(elem, cookielet) {
		var val = 0;

		if($(elem).parents("div.p-wrapper").hasClass("p-collapse")){
			val = 1;
		}
		$.writeCookielet("STUB_BROWSE_INFO",cookielet,val);
	}
	
	function updateWidgets() {
		
		if(typeof(bNoBrowseHistory) != "undefined" && bNoBrowseHistory ){
			$("#viewHistory .p-widget h2 a").click();
		}	
		
		var ue = $.readCookielet("STUB_BROWSE_INFO","ue");
		
		if(ue == 0 && !$("#upcomingEvents .p-wrapper").hasClass("p-collapse")) {
			$("#upcomingEvents .p-widget h2 a").click();	
		}		
		if(ue != "0" && ue != "1"){
			$("#upcomingEvents .p-widget h2 a").click();	
		}
		
		if(typeof(upcomingEvent) != "undefined" && upcomingEvent == "false"){
			$("#upcomingEvents").addClass("hideOnLoad");
		}
	}

	/* ============== Compare popup ===============*/
	/**/

	//;(function($){
	var qty = ""; //based on condition value will change
	var isTicketFeatureRow = false;
	var emptyTD = '<td rowspan="8" class="empty leftborder">&#160;</td>';
	var deliveryStr = "&#160;";
	var listingAttributeList = new Array();	
	var actualRow = 0; 
	var listingId = 0;
	var isRemoveOn = false;
	

	function openCheckout(id){
		if(buyQuantity > 9)
			window.location = buyUrl+"?c=1&ticket_id="+id+"&quantity="+checkoutQuantity;
		else
			window.location = buyUrl+"?c=1&ticket_id="+id+"&quantity="+buyQuantity;
		
		$(".ui-dialog-titlebar-close").trigger("click");
	}

	function removeCompareItem(listingObj){
		if(!isRemoveOn){
			isRemoveOn = true;
			listingId = listingObj.id;
	
			$('#td0'+listingId).html("&#160;&#160;&#160;&#160;&#160;").removeClass("features2").addClass("remove");
			$('#td1'+listingId).html("&#160;").removeClass("features1").addClass("remove");
			$('#td2'+listingId).html("&#160;").removeClass("features2").addClass("remove");
			$('#td3'+listingId).html("&#160;").removeClass("features1").addClass("remove").html('<nobr>&#160;&#160;&#160;<img src="'+staticUrl+'/resources/mojito/img/pattern/phoenix/throbber_24.gif" class="textmiddle"/> Removing</nobr>');
			$('#td4'+listingId).html("&#160;").removeClass("features2").addClass("remove");
			$('#td5'+listingId).html("&#160;").removeClass("features1").addClass("remove");
			$('#td6'+listingId).html("&#160;").removeClass("features2").addClass("remove");
			$('#td7'+listingId).html("&#160;").removeClass("features2").addClass("remove");	
	
			//totCol--;
			actualRow = actualRow - 1;
	
			var ticketlistmap = "";
			/*if($.browser.msie){
				ticketlistmap = document.getElementById("ticketlistmap");
			}else{
				ticketlistmap = document.getElementById("ticketlistmap1");
			}*/

			ticketlistmap = document.getElementById("ticketlistmap");
			
			ticketlistmap.removeCompareItem(comparableTickets[listingId]);
	
			//window.setTimeout(removeRow, 500, listingId);
			var current_timer_remRow = window.setTimeout(function () { 
		                removeRow();
		           }, 1500);
			
			//add empty column at the end				
			//window.setTimeout(appendEmptyRow, 1500, emptyTD);
			var current_timer_emptyRow = window.setTimeout(function () { 
		                appendEmptyRow(1);
		            }, 1540);		
		}
	}
	function appendEmptyRow(num){		
		//ADD EMPTY ROW IN CASE LISTING LESS THAN 5 ITEMS			
		for(var j=0;j<num;j++){
			$('#compareTicket .compareTable tr:first').append(emptyTD);
		}
		isRemoveOn = false;
	}

	function removeRow(){
			
		$('#td0'+listingId).remove();
		$('#td1'+listingId).remove();
		$('#td2'+listingId).remove();
		$('#td3'+listingId).remove();
		$('#td4'+listingId).remove();
		$('#td5'+listingId).remove();
		$('#td6'+listingId).remove();
		$('#td7'+listingId).remove();

		if(actualRow<=2)
			hideRemoveLink();

	}

	function hideRemoveLink(){
		$('.pipe').css("visibility","hidden");
		$('.remLink').css("visibility","hidden");
	}
	function renderListing(){

		var td11 = '<td class="features"> Price <br/> <span> per ticket </span></td>';
		var td21 = '<td class="features3"> Zone/Section </td>';
		var td31 = '<td class="features"> Row </td>';
		var td41 = '<td class="features3"> Seats </td>';
		var td51 = '<td class="features" > Qty </td>';
		
		if(isLogisticAvailable == "true")
			var td61 = '<td class="features3"> Delivery method </td>';
		else
			var td61 = '<td class="features3"> Electronic delivery</td>';
		
		
		var td71 = '<td class="features"> Ticket features </td>';
		var td81 = '<td class="features">&#160;</td>';
		
		var marginleft = "margin-left:-23px;";
		if($.browser.msie){
			marginleft = "margin-left:20px;";
		}
		
		var button = "";
		var ticketFeature = "&#160;";
		//alert(listingAttribute.length);
		var len=listingAttribute.length;
		var compticketsLen = comparableTickets.length;
		var re = new RegExp(",","g");
		var compareObj = "";
		var qtyForUrl = 0;
		var attributeId = 0;
		var attributeDesc = "";

		for(var i=0;i<compticketsLen;i++){
			compareObj = comparableTickets[i];
			qty = compareObj.quantity;
			qtyForUrl = qty;
			//check for split quantity
			if(compareObj.split){
				qty = "Up to " + qty;
			}

			if(compticketsLen ==2)
				button = '<button type="button" onClick="checkoutQuantity='+qtyForUrl+';totCol='+compareObj.listingId+';" class="btn-buy white buybtn" id="buy'+i+'"></button><br/><br/>';
			else
				button = '<button type="button" onClick="checkoutQuantity='+qtyForUrl+';totCol='+compareObj.listingId+';" class="btn-buy white" id="buy'+i+'"></button><label class="pipe">|</label><a href="javascript:void(0);" id="'+i+'" class="remLink">Remove </a><br/>';
			
			td11 += '<td class="features2 leftborder" id="td0' + i + '"> '+ compareObj.currentPrice +' </td>';				
			var section = splitText(compareObj.venueConfigSectionAlias);
			td21 += '<td class="features1 leftborder" id="td1' + i + '"> '+ section +' </td>';
			row = compareObj.rowDesc;
			
			if(typeof(row) != "undefined"){
				if(row.indexOf(",")!= -1)
					row += " (piggyback)";
				row = row.replace(re,", ");
			}

			td31 += '<td class="features2 leftborder" id="td2' + i + '"> '+row+' </td>';

			if(compareObj.seats != null && compareObj.seats != 'null')
				row = compareObj.seats.replace(re,", ");
			else{
				row = "Not Applicable";
			}
			td41 += '<td class="features1 leftborder" id="td3' + i + '"> '+row+' </td>';
			td51 += '<td class="features2 leftborder" id="td4' + i + '"> '+qty+' </td>';
					

			if(compareObj.isCharity){
				ticketFeature += '<span class="icon-14 icon-charity">&#160;</span>'; 
			}
			if(compareObj.isExclusiveOffer){
				ticketFeature += '<span class="icon-14 icon-offer">&#160;</span>'; 
			}
			if(compareObj.isParkingPassIncluded){
				ticketFeature += '<span class="icon-14 icon-parking">&#160;</span>';
			}
			if(compareObj.isWheelChair){
				ticketFeature += '<span class="icon-14 icon-wheelchair">&#160;</span>';				
			}
			ticketFeature += '<br/>';
			
			if(compareObj.isElectronicTicket){
					if(isLogisticAvailable=="true")
						deliveryStr = "Electronic <br/>";
					else
						deliveryStr = '<span class="icon-14 icon-graycheckmark">&#160;</span> <br/>';
									
			}else if(compareObj.isInstanceDelivery){
				if(isLogisticAvailable=="true")
					deliveryStr = "Electronic <br/>";
				else
					deliveryStr = '<span class="icon-14 icon-graycheckmark">&#160;</span> <br/>';
				
				deliveryStr += "<label>Instant Download</label><br/><br/>";
			}else{
				if(compareObj.DeliveryOption != null){
					if(compareObj.DeliveryOption.isManualDelivery){
						deliveryStr += "Pickup<br/> <span>At will call/kiosk</span><br/>";
					}else{					
						deliveryStr += "FedEx";
					}
				}else{
					deliveryStr = "&#160;";
				}
			}
			td61 += '<td class="features1 leftborder"  id="td5' + i + '"> '+ deliveryStr+' </td>';				
			
			//iterate through listing attribute list
			list = compareObj.listingAttributeIdList;
			if(list){
				var listObj = compareObj.listingAttributeIdList.list.source;
				if(listObj.length >0){
					ticketFeature += "<ul style='"+marginleft+"'>";
					for(var j=0;j<listObj.length;j++){
					   attributeId = listObj[j];
					   attributeDesc = listingAttribute[attributeId].description;
					   if(attributeDesc != "Parking Pass" && attributeDesc != "Wheelchair seating"){
						   ticketFeature += "<li>"+attributeDesc +"</li>";
					   }
					}
					ticketFeature += "</ul>";
				}
			}			

			if(ticketFeature.length > 11){
				isTicketFeatureRow = true;
			}
			td71 += '<td  class="features2 leftborder" id="td6' + i + '"> '+ ticketFeature +' </td>';
			td81 += '<td class="features2 leftborder padd" id="td7' + i + '">'+button+'</td>';
			deliveryStr="";				
			button ="";
			ticketFeature="&#160;";
			row = "";
			compareObj = "";
			attributeId = "";
			attributeDesc = "";
		}

		actualRow = i; // hold the number of td containing data

		//append empty row, if any required
		if(actualRow<5){			
			for(var j=actualRow;j<5;j++){
				td11 += emptyTD;				
			}
		}

		//append td to tr
		td11 = '<tr>'+td11+'</tr>';
		td21 = '<tr>'+td21+'</tr>';
		td31 = '<tr>'+td31+'</tr>';
		td41 = '<tr>'+td41+'</tr>';
		td51 = '<tr>'+td51+'</tr>';
		td61 = '<tr>'+td61+'</tr>';		
		td81 = '<tr>'+td81+'</tr>';

		if(isTicketFeatureRow)
			td71 = '<tr>'+td71+'</tr>';
		else
			td71 = '<tr style="display:none">'+td71+'</tr>';

		strHTML = '<table class="compareTable" cellspacing="0">'+td11 +td21+td31+td41+td51+td61+td71+td81+'</table>';
		return strHTML;
	}
	/* ======+====== Bindings ======+====== */
	$(function() {		

		$("#eventSummary").panel({bgFullClass:'p-bg-grblu-center', bgBottomClass:'p-bg-grblu-bottom', bgTopClass:'p-bg-grblu-top'});	

		$("#fanProtectLink").overlay({align:'relative',width:440,trigger:'click'});
		$("#fanProtectLinkPA").overlay({align:'relative',width:440,trigger:'click'});
		//Events associated with Help overlay and formatting
		$(".formathelp").overlay({align:'relative',overlayId:'formatHelpLayer',width:510,open:$.formatHelp});

		
		var modalAlert = typeof(isEventAlert) !='undefined' && isEventAlert;
		var eventInfo = {align:'relative',width:400,preferedAlignment:'right'};
		if(modalAlert) {
			eventInfo = {modal:true,showCloseIcon:false,width:400,closeSelector:'#eventInfoLayer #btnOk'};
		}
		$("#eventInfoLink").overlay(eventInfo);		
		$("#continue").overlay({modal:true,align:'centered',width:400,source:'#continuediv',closeSelector:'#continuediv .Cancel'});	
		$("#seatingNote").overlay({modal:false,align:'relative',source:'#seatingNotesdiv',width:440});			

		//RCP for widget
		$(".p-widget").panel({bgTopClass:'p-bg-hdrblu-lrg p-hdr-lrg',	blSliceClass:'p-collapsable', brSliceClass:'p-collapsable'});
		
		$("#viewHistory .eventlist li").live("mouseover", function(){
			$(this).addClass('hover');
		});
		$("#viewHistory .eventlist li").live("mouseout", function(){ 
			$(this).removeClass('hover');
		});				
		$("#upcomingLink").click( function() {
			toggleCookie(this, "ue");
		});
		
		$('#setPriceAlert').livequery('click', function(){
			try{
				var s=s_gi(s_account);
				s.objectId = "PA654321";
				s.tl(this,'o','Price Alert Button');
			}catch(e){
			}
			//empty div every time when setpricealert button is clicked
			$('#priceAlertDiv').html();
			
			$.getJSON(priceAlertUrl + '&action=view&format=json&jsoncallback=?', function(resp){			
				$('#priceAlertDiv').html(resp.data);
				$('#setPriceAlert').overlay({modal:true,overlayId:'priceAlertLayer',width:600,source:'#priceAlertDiv',trigger:'load'});					
				$('#price_error').attr("style","margin-left: 10px;display:none;");			
				$('#zone_error').attr("style","display:none;");			
			});		
		});
		$('#removeAlert').livequery('click', function(){		
			//empty div every time when removeAlert button is clicked
			$('#removeAlertDiv').html();
			
			$.getJSON(deleteAlertUrl + '&action=view&format=json&jsoncallback=?', function(resp){			
				$('#removeAlertDiv').html(resp.data);
				$('#removeAlert').overlay({modal:true,overlayId:'removeAlertLayer',width:390,closeSelector:'#deletePriceAlert #btnNo',source:'#removeAlertDiv',trigger:'load'});
				$("#removeAlertDiv #btnYes").attr("type","button");			
			});		
		});
		$('#editAlert').livequery('click', function(){
			//empty div every time when setpricealert button is clicked
			$('#priceAlertDiv').html();
			
			$.getJSON(priceAlertUrl + '&action=view&format=json&jsoncallback=?', function(resp){			
				$('#priceAlertDiv').html(resp.data);
				$('#editAlert').overlay({modal:true,overlayId:'priceAlertLayer',width:600,source:'#priceAlertDiv',trigger:'load'});			
				$('#price_error').attr("style","margin-left:10px;display:none;");			
				$('#zone_error').attr("style","display:none;");						
			});		
		});
		
		//call to js function
		$("#compareTicket a.remLink").livequery("click", function(){
			removeCompareItem(this);
		});

		$('#compare').livequery('click',function() {					
			$('#compareTicket').html(renderListing());
			$('#compareTicketDiv').removeClass('hideOnLoad');			
			$("#compare").overlay({modal:true,align:'centered',overlayId:'compareTicketsLayer',width:800,source:'#compareTicketDiv',trigger:'load'});

			try{
				var s=s_gi(s_account);
				var nameArr = pageName.split("/");
				s.pageName = nameArr[0] + "/" +nameArr[1] + "/compare_tickets";
				s.t();
			}catch(e){				
			}
			//This css is applied , in case after content is loded a white border is mising on left side of overlay
			// By applying zoom css, it works fine.
			$(".ov-slice-tr").attr("style", "zoom:1;");
		});
		
		$("#compareTicket .btn-buy").livequery('click', function(){				
			openCheckout(totCol);
		});	

		//set 'sell for this event' middle aligned if, event info link is absent
		if(typeof(EventInfoflag) != "undefined" && EventInfoflag == "false"){		
			$("#sellEvent").css("margin-top","12px");
		}

		if(typeof(isPriceAlertsEnabled) != "undefined" && isPriceAlertsEnabled == "true"){
			$("#fanProtectLink").removeClass("hideOnLoad");		
		}	

		$(document).ready(function() {
			updateWidgets();			
			if(modalAlert) {
				$("#eventInfoLink").trigger('click');
			}
			if(typeof(TktFilterMapFlashObj) != "undefined")			
				$("#tktFilterMap").flash(TktFilterMapFlashObj, { version: 8 });
			if(typeof(TktListingsMapFlashObj) != "undefined")			
				$("#tktListingsMap").flash(TktListingsMapFlashObj, { version: 8 });

 		});
	});	
})(jQuery);

