var fullURL = window.location.href;
var promoID = "";
var modelParam = "cs:i:v="
var promoParam = "promoID=";
var deeplinkParam = "deeplink=";

jQuery(document).ready(determinePageContext);
 
function determinePageContext() {
	// register handler for promo events
	// This needs to be done here since this function will run before EventManager.addHandlers()
	registerPromoHandler();
	//
	var urlHasPromo = ((fullURL.indexOf(promoParam) > -1) && (getParamValue(fullURL, promoParam) != ""));
	var urlHasDeeplink = ((fullURL.indexOf(deeplinkParam) > -1) && (getParamValue(fullURL, deeplinkParam) != ""));
	if (urlHasPromo) {
		promoID = getParamValue(fullURL, promoParam);
		// 'true' param indicates this is on page load
		reskin(promoID, true);
	} else {
		restoreStandard();	
		if (urlHasDeeplink) {
			var deeplinkType = getParamValue(fullURL, deeplinkParam);
			switch (deeplinkType) {
				case "offer":
					// See Current Offers will appear after a delay for visual effect
					setTimeout(showOffers, 1000);
					break;
				case "quote":
					// Get A Quote will appear after a delay for visual effect
					setTimeout(showGAQ, 1000);
					break;
				case "inventory":
					// Search Inventory will appear after a delay for visual effect
					var thisModel = "";
					var urlHasModel = ((fullURL.indexOf(modelParam) > -1) && (getParamValue(fullURL, modelParam) != ""));
					if (urlHasModel) {
						thisModel = getParamValue(fullURL, modelParam);
						var modelArr = thisModel.split(":");
						if (modelArr[1] != "") {
							thisModel = modelArr[1];
						}
					} 
					var paramOb = {
						make:make,
						model:thisModel,
						search:"new"
					};
					initDealerLink("VehicleSearchResults", "Search Inventory", paramOb);
					break;
				default:
					// no deeplink so standard page will be shown (don't need to do anything).
			}
		}
	}
}

function getPromoID() {
    thisMovie("lslp_promo_image1swf").getPromoIDFromJS(promoID);
}

function getParamValue(url, param) {
	var urlSegment = url.slice(url.indexOf(param));
	var endIndex = (urlSegment.indexOf("&") > -1) ? urlSegment.indexOf("&") : urlSegment.length;
	return urlSegment.slice(param.length, endIndex);
}

function registerPromoHandler() {
	var handler = function(eventName, publisherData, subscriberData) {
		var lslpTag = new LslpPixelTag(publisherData);
		lslpTag.writePixelTag();
	}
	// Create a new instance of EventHandler
	var newHandler = EventManager.getEventHandlerInstance("Cobalt", handler);
	EventManager.subscribe({
		eventName : "com.cobaltgroup.ws.view.promo",
		callback : "execute",
		scope : newHandler
	});
}

function restoreStandard(p_isPageView) {	
	promoMode = false;
	// Remove any existing promotions before displaying a new one. 
	jQuery("#promoContainer").remove();
	// Banner
	jQuery("#lslp_promo_image1").css("display", "block");
	// VirtualInventory
	jQuery("#layoutWrapper h2").css("display", "block");
	jQuery("#lslpTabs").css("display", "block");
	jQuery("#lslp_mainFieldset").css("visibility", "visible");
	jQuery("#lslp_cissOfferContainer").css("visibility", "visible");
	// Map
	jQuery("#mapHeader").css("display", "block");
	jQuery("#mapWrapper").css("visibility", "visible");
	jQuery("#dmaSearchFormWrapper").css("visibility", "visible");
	jQuery("#dmaSearchLoadImage").css("visibility", "visible");
	jQuery("#userLinks").css("display", "block");
	//
	// Fire page view pixel tag if this is on page load, and promoID is not current
	var isPageView = (p_isPageView) ? p_isPageView : false;
	if (isPageView) {
		// new framework - fire normal pageView tag
		var lslpTag = new LslpPixelTag();
		lslpTag.writePixelTag(); 
	}
}

// Called from the Banner SWF when a promotion's target is "page".  
function clearPage(id) {	
	// Remove any existing promotions before displaying a new one. 
	jQuery("#promoContainer").remove();
	// Banner
	jQuery("#lslp_promo_image1").css("display", "none");
	// VirtualInventory
	jQuery("#layoutWrapper h2").css("display", "none");
	jQuery("#lslpTabs").css("display", "none");
	jQuery("#lslp_mainFieldset").css("visibility", "hidden");
	jQuery("#lslp_cissOfferContainer").css("visibility", "hidden");
	// Map
	jQuery("#mapHeader").css("display", "none");
	jQuery("#mapWrapper").css("visibility", "hidden");
	jQuery("#dmaSearchFormWrapper").css("visibility", "hidden");
	jQuery("#dmaSearchLoadImage").css("visibility", "hidden");
	jQuery("#userLinks").css("display", "none");

	reskin(id);
}

function redirect() {
	var url = window.location.href;
	var qIndex = url.indexOf("?");
	if (qIndex > -1) { 
		url = url.slice(0, qIndex);
	}
	window.location.href = url;
}

/* 
*  tagNGo() is used when linking to a 3rd party page.  We first fire a Cobalt PixelTag and then open the page.
*  aInfo should have 2 elements.  [0] should be the pageLabel.  [1] should be the destination URL. 
*  [2] will be "tb" if the new URL should open in a Thickbox, if empty then a new window will open.
*  [3] will be the width of the new window/Thickbox.  [4] will be the height of the new window/Thickbox.
*  This function is also called by the Banner SWF when the target is "js".  
*/
function tagNGo(aInfo) {
	var promoPixelTag = {
		pageLayout : 'linkout_' + aInfo[0],
		pageName : aInfo[0],
		pageLabel : 'linkout_' + aInfo[0] + "_HomePage&cs:lo=" + aInfo[0] ,
		dma:dmaCode
	};
	EventManager.publish({
		eventName:'com.cobaltgroup.ws.view.promo',
		publisherData:promoPixelTag
	});

	var goWidth = (aInfo[3] != undefined) ? "width=" + aInfo[3] : "width=720";
	var goHeight = (aInfo[4] != undefined) ? "height=" + aInfo[4] : "height=500";

	if ((aInfo[2] != undefined) && (aInfo[2].toLowerCase() == "tb")) {
		tb_show("", aInfo[1] + "?KeepThis=true&TB_iframe=true&TB_keepScrollbars=true&" + goWidth + "&" + goHeight, null);
		jQuery("#TB_closeAjaxWindow").html("<a id='TB_closeWindowButton' title='Close' href='#'>close</a>");
		jQuery("#TB_closeWindowButton").click(tb_remove);
		/* Fire a Spotlight pixel tag (matched to spotlight_pixeltags.js under make-specific LSLP MLM public folder */
		PixelTagUtility.fireThirdPartyPixelTag({
			thisEventId:51
		});
	} else {
		var NewWindow = window.open(aInfo[1],"newWin",goWidth + "," + goHeight + ",left=0,top=0,toolbar=No,location=No,scrollbars=Yes,status=No,resizable=Yes,fullscreen=No"); 
		NewWindow.focus();
	}
}

function initDealerLink(dealerPage, title, paramOb) {
	// Define pixel tag objects:
	// 1. Pixel tag that will fire on opening the DealerLink form:
	// -- we use 'com.cobaltgroup.ws.view.promo' since this event is already registered - see above
	var pixelTagOnOpen = {
		eventName : "com.cobaltgroup.ws.view.promo",
		pageLabel:"DealerLink",
		dma:dmaCode
	};
	// 2. Pixel tag that will fire on "Go" click:
	var pixelTagOnGo = {
		eventName : "com.cobaltgroup.ws.action.link",
		pageLabel:"DealerLink_Go",
		dma:dmaCode
	};
	DealerLink.showDealerLink(dealerPage,pixelTagOnOpen,pixelTagOnGo,paramOb);
	//
	if ((title != "") && (title != undefined)) {
		jQuery("#TB_ajaxWindowTitle").text(title);
	}
	//
	return false;
}

function showOffers() {
	jQuery("#lslpTab2").click();
}

function showGAQ() {
	var tbGAQ = tb_show("Get a Quote", "#TB_inline?width=593&height=238&inlineId=gaqFormWrapper", null);
	var thisRecord = jQuery("#gaqFormWrapper");
	jQuery(tbGAQ).ready(function () {
		jQuery("#lslp_gaq_vehImgCont").empty();
		// tweak Thickbox CSS
		jQuery("#TB_title").css("height", "30px");
		jQuery("#TB_ajaxWindowTitle").css("padding-top", "4px");
		jQuery("#TB_ajaxContent").css("overflow","hidden");
		jQuery("#gaq_fromMapField").val("false");
		jQuery("#gaq_fromDirectory").val("false");
		positionGAQDealerDropdown();
		getDealersGAQ();
		var urlHasModel = ((fullURL.indexOf(modelParam) > -1) && (getParamValue(fullURL, modelParam) != ""));
		var modelArr = [];
		if (urlHasModel) {
			var thisModel = getParamValue(fullURL, modelParam);
			var modelArr = thisModel.split(":");
			if (modelArr[1] != "") {
				jQuery("#gaq_model").val(modelArr[1]).triggerHandler("change");
			}
		} 
		if ((modelArr[1] == undefined) || (modelArr[1] == "")) {
			jQuery("#gaq_model").val(taxonomySearch.getModel()).triggerHandler("change");
			jQuery("#gaq_trim").val(taxonomySearch.getTrim()).triggerHandler("change");
		}
		EventManager.publish({
			eventName:'com.cobaltgroup.ws.view.promo',
			publisherData:{ pageLabel:"GAQ" }
		});
	});
}
