var isSafari = (/Safari/.test(navigator.userAgent));
var isSafari2 = (/AppleWebKit\/4/.test(navigator.userAgent));
/**
* Build And Price SWFObject 1.5 Injection
* @author Ryan Doll
* @version 0.1
*/

var orgHistoryLength = 0;
var clearHistoryInterval = null;

var transitionSWF 	= null;
var bpSWF 			= null;
var nextScreen		= null;
var isDeepLink      = false;

var _locale 		= "";
var _postalCode 	= "";
var _province 		= "";
var _customerVehicleId = "";
var _modelYearId    = "";
var _aCode 			= "";
var _vehicleType 	= "";
var _stateString 	= "";
var _section 		= "";
var _page 			= "";
var _dealerConnect  = false;
var _modelIdExcludes = "";
var _context        = "";

var bnpWin;
var bnpIsOpen = false;

//var bnpTimer = new DebugTimer();
function OpenFlash(x, y, FlashVars) {
	bnpIsOpen = true;
    //if(!orgHistoryLength) orgHistoryLength = history.length;
    orgHistoryLength = history.length;
    //bnpTimer.mark("Start OpenFlash");
	$("#rightcontent_main select").css("visibility","hidden");
	$("#msrp_legal").css("display","none");

	if (window.ActiveXObject) {
		var mask = document.createElement("iframe");
		mask.id = "bnpMask";
		mask.style.backgroundImage = "none";
		mask.style.backgroundColor = "000";
		mask.style.border = "0px";
		mask.style.filter = "alpha(opacity=0)";
		mask.style.display = "block";
		mask.className = "overlay";
		mask.style.zIndex = 80;
		document.body.appendChild(mask);
	}
    
    // JQUERY CURVY CORNERS
    //bnpTimer.mark("Start curvy corners");
    /*$("#bnp_legal").corner({
        tl: { radius: 15 },
        tr: { radius: 15 },
        bl: { radius: 15 },
        br: { radius: 15 },
        antiAlias: true,
        autoPad: true
    });*/
    //bnpTimer.mark("End curvy corners");
    
    window.scrollTo(0,0);
	// Adjust for difference in Flash XY and Screen XY - This can be adjusted.
	var _x = x - 120;
	var _y = y + 10;
	
	setFlashVars(FlashVars);
	
/*	alert("OpenFlash()\nlocale=" + _locale +
			"\npostalCode=" + _postalCode + 
			"\nprovince=" + _province +
			"\ncustomerVehicleId=" + _customerVehicleId + 
		    "\nmodelyearid=" + _modelYearId + 
			"\nacode=" + _aCode +
			"\nvehicletype=" + _vehicleType +
			"\nstatestring=" + _stateString + 
			"\nsection=" + _section + 
			"\npage=" + _page + 
		    "\ndealerConnect=" + _dealerConnect +
		    "\nmodelIdExcludes=" + _modelIdExcludes);
*/
	
	if (isSafari2) {
		showBlackout("bpHolder");
	    document.getElementById("bpHolder").style.visibility="visible";
		BuildBAndP();
		zoomInComplete(FlashVars.context);
	} else {
		// Flash injection - Do not change.
		transitionSWF = new SWFObject('/flash/buildandprice'+_context+'/swf/zoomFlip.swf', 'transition', '965', '570', '9.0.0', '#FFFFFF');
		transitionSWF.useExpressInstall('/flash/buildandprice'+_context+'/buildandprice/swf/expressInstall.swf');
		transitionSWF.addParam('wmode', 'transparent');
		transitionSWF.addParam('base', '.'); // Only change this one.
		transitionSWF.addParam('allowScriptAccess', 'always');
		
		// Flash Vars
		transitionSWF.addVariable("zoomX", _x);
		transitionSWF.addVariable("zoomY", _y);
		transitionSWF.write('transitionHolder');
	    document.getElementById("transitionHolder").style.visibility = "visible";
	    showBlackout("transitionHolder");
		BuildBAndP();
    }
    //bnpTimer.mark("End OpenFlash");
}
function OpenLincolnFlash(x, y, FlashVars) {
    if(!FlashVars) FlashVars = {};
    FlashVars.context = "/lincoln";
    OpenFlash(x, y, FlashVars);
}

function openBNP (acode, vehicletype, FlashVars){
	if(!FlashVars) FlashVars = {};
	FlashVars.acode = acode;
	FlashVars.vehicletype = vehicletype;
	OpenFlash(FlashVars);
}

function setFlashVars(FlashVars) {
    if(FlashVars.locale) _locale = FlashVars.locale.replace("_","-");  // Need to adjust for the Flash XML structure.
    if(FlashVars.postalCode) _postalCode = FlashVars.postalCode;
    if(FlashVars.province) _province = FlashVars.province;
    if(FlashVars.customerVehicleId) _customerVehicleId = FlashVars.customerVehicleId;
    if(FlashVars.modelYearId) _modelYearId = FlashVars.modelYearId;
    if(FlashVars.aCode) _aCode = FlashVars.aCode;
    if(FlashVars.vehicleType) _vehicleType = FlashVars.vehicleType;
    if(FlashVars.stateString) _stateString = FlashVars.stateString;
    if(FlashVars.section) _section = FlashVars.section;
    if(FlashVars.page) _page = FlashVars.page;
    if(FlashVars.dealerConnect) _dealerConnect = FlashVars.dealerConnect;
    if(FlashVars.modelIdExcludes) _modelIdExcludes = FlashVars.modelIdExcludes;
    if(FlashVars.context) _context = FlashVars.context;
}

function BuildBAndP() {
	//bnpTimer.mark("Start BuildBAndP");
	// Flash injection - Do not change.
	bpSWF = new SWFObject('/flash/buildandprice'+_context+'/shellLoader.swf', 'BAndP', '965', '570', '9.0.0', '#FFFFFF');
	bpSWF.useExpressInstall('/flash/buildandprice'+_context+'/swf/expressInstall.swf');
	bpSWF.addParam('wmode', 'transparent');
	bpSWF.addParam('base', '.'); // Only change this one.
	bpSWF.addParam('allowScriptAccess', 'always');
	
	// Flash Vars
	bpSWF.addVariable("locale", _locale);
	bpSWF.addVariable("postalCode", _postalCode);
	bpSWF.addVariable("province", _province);
	bpSWF.addVariable("customerVehicleId", _customerVehicleId);
    bpSWF.addVariable("modelyearid", _modelYearId);
	bpSWF.addVariable("acode", _aCode);
	bpSWF.addVariable("vehicletype", _vehicleType);
	bpSWF.addVariable("statestring", _stateString);
	bpSWF.addVariable("section", _section);
	bpSWF.addVariable("page", _page);
    bpSWF.addVariable("dealerConnect", _dealerConnect);
    bpSWF.addVariable("modelIdExcludes", _modelIdExcludes);
	bpSWF.write('bpHolder');
    //bnpTimer.mark("End BuildBAndP");
}

function clearHash() {
    if(orgHistoryLength<history.length) history.go(orgHistoryLength-history.length);
    clearHistoryInterval = setInterval(function() {
        if(document.location.hash && document.location.hash.length > 1) history.go(-1);
        else clearInterval(clearHistoryInterval);
    }, 1000);
    /*
    if(SWFAddress) {
        SWFAddress.resetStatus();
        clearHistoryInterval = setInterval(function() {
            if(document.location.hash && document.location.hash.length > 1) SWFAddress.back();
            else clearInterval(clearHistoryInterval);
        }, 1000);
        
    }
    */
}

function changeScreen(screenName) {
    //clearHash();
	_section = screenName;
	nextScreen = screenName;
    if(isSafari) document.getElementById("transitionHolder").style.top = "0px";
	hideAll();
    if (screenName == "buildandprice") {
    	// Don't know how to maintain current page if one exists
    	isDeepLink = true;
    	_page = "vehicletype";
    	if(document.location.hash && document.location.hash.length > 1) document.location.hash = "/buildandprice/vehicletype///";
        resetBuildAndPrice();
    }
	if(isSafari2) {
		flipComplete();
	} else {
		try {
			document.getElementById("transition").flip();
		} catch(e) {
			// Not sure why this happens
			//alert('else catch' + e);
			//debug("transition flipComplete() exception = " + e);
			flipComplete();
		}
	}
}

function showApp() {
    if(isSafari) {
        setTimeout(function() {
            document.getElementById("transitionHolder").style.top = "-5000px";
        }, 1000);
    }
	document.getElementById("BAndP").style.visibility = "visible";
	if (isSafari2) {
		setTimeout(function() {
			var legal = document.getElementById("bnp_legal");
			legal.style.display = "block";
		}, 1000);
	} else {
    	document.getElementById("bnp_legal").style.display = "block";
   	}
    
}

function hideApp() {
	document.getElementById("BAndP").style.visibility = "hidden";
    document.getElementById("bnp_legal").style.display = "none";
}

function flip() {
	hideApp();
	document.getElementById("transition").flip();
}

function zoomInComplete() {
	showApp();
}

function zoomOutComplete() {
	// Destroy the SWFObject - Note:  Must do via a setTimeout, or else Firefox Crashes.
	setTimeout ("destroySWFObject()", 500 );
	var holder = (isSafari2) ? "bpHolder" : "transitionHolder";
    document.getElementById(holder).style.visibility = "hidden";
    hideBlackout(holder);
    window.focus();
    $("#rightcontent_main select").css("visibility","visible");
}

function resetBuildAndPrice() {
    var bnp = document.getElementById("bpHolder");
    bnp.innerHTML = "";
}

function destroySWFObject() {
    resetBuildAndPrice();
	var trans = document.getElementById("transitionHolder");
    trans.innerHTML = "";
    var mask = document.getElementById("bnpMask");
	if(mask) {
		mask.style.display = "none";
		mask.parentNode.removeChild(mask);
	}
    clearHash();
    //bnpTimer.clear();
}

function compare() {
	document.getElementById("compare").style.display = "block";
	document.getElementById("compare").style.visibility = "visible";
	document.getElementById("savedvehicles").style.display = "none";
	document.getElementById("savedvehicles").style.visibility = "hidden";
	document.getElementById("bnpTab").style.display = "block";
	//showBlackout("blackoutloader");
}

function savedvehicles() {
	document.getElementById("savedvehicles").style.display = "block";
	document.getElementById("savedvehicles").style.visibility = "visible";
	document.getElementById("compare").style.display = "none";
	document.getElementById("compare").style.visibility = "hidden";
	document.getElementById("bnpTab").style.display = "block";
}

function hideAll() {
	document.getElementById("BAndP").style.visibility = "hidden";
	document.getElementById("compare").style.visibility = "hidden";
	document.getElementById("savedvehicles").style.visibility = "hidden";
	document.getElementById("bnpTab").style.display = "none";
    document.getElementById("bnp_legal").style.display = "none";
}

function startingScreen(screenName) {
	nextScreen = screenName;
	flipComplete();
}

function buildVehicle(modelYearId, acode, stateString, customerVehicleId) {
    //alert('Start - buildVehicle()\nmodelYearId=' + modelYearId + '\nacode=' + acode + '\nstateString=' + stateString + '\ncustomerVehicleId=' + customerVehicleId);
	//_modelYearId = modelYearId;
    _aCode = acode;
    //_vehicleType = "car";
    _stateString = (stateString) ? stateString : "";
    _customerVehicleId = customerVehicleId;
    _section = "buildandprice";
    _page = "options";
    
    isDeepLink = true;
    changeScreen("buildandprice");
    //alert('End - buildVehicle()');
}

function saveVehicle(acode, stateString, vehicleType, accessories, customerVehicleId) {
	try {
	    var screen = "savedvehicles";
	    if(!stateString) stateString = "";
	    if(!accessories) accessories = "";
	    var vhclParam = (customerVehicleId) ? "&vehicleId=" + customerVehicleId : "";
	    loadBnpTabPage(screen, root+"/garage/save.do?acode=" + acode + "&str=" + stateString + "&vehicleType=" + vehicleType + "&acc=" + accessories + vhclParam + "&ajax=" + screen);
	    changeScreen(screen);
	} catch(e) {
		//alert("saveVehicle() exception = " + e);
	}
}

function compareVehicle(modelYearId, acode, stateString) {
	var screen = "compare";
    if(!acode) acode = "";
    if(!stateString) stateString = "";
    // TODO: Uncomment to enable animation
    //useCompareAnimation = (acode || modelYearId);
    loadBnpTabPage(screen, root+"/vehicle_comparison.jsp?modelYearId=" + modelYearId + "&acode=" + acode + "&str=" + stateString);
    //changeScreen(screen);
}

function printVehicle(modelYearId, acode, stateString, accessories, retailDownPayment, leaseDownPayment, retailTerm, leaseTerm, retailAPR, leaseAPR, leaseAnnualKm, province, incentivesSelected) {
    if(retailAPR) retailAPR = retailAPR.replace("%","");
    if(leaseAPR) leaseAPR = leaseAPR.replace("%","");
    var obj = {acode:acode, str:stateString, acc:accessories, retailDownPayment:retailDownPayment, leaseDownPayment:leaseDownPayment, retailTerm:retailTerm, leaseTerm:leaseTerm, retailAPR:retailAPR, leaseAPR:leaseAPR, leaseAnnualKm:leaseAnnualKm, province:province, incentivesSelected:incentivesSelected };
    var url = root + "/print.do?";
    var ampersand = false;
    for(var prop in obj) {
        if(obj[prop]) {
            if (ampersand) url += "&";
            else ampersand = true;
            url += prop + "=" + obj[prop];
        }
    }
    bnpPopUp(url);
}

function sendVehicle(modelYearId, acode, stateString, accessories, retailDownPayment, leaseDownPayment, retailTerm, leaseTerm, retailAPR, leaseAPR, leaseAnnualKm, province, incentivesSelected) {
    if(retailAPR) retailAPR = retailAPR.replace("%","");
    if(leaseAPR) leaseAPR = leaseAPR.replace("%","");
    var obj = {acode:acode, str:stateString, acc:accessories, retailDownPayment:retailDownPayment, leaseDownPayment:leaseDownPayment, retailTerm:retailTerm, leaseTerm:leaseTerm, retailAPR:retailAPR, leaseAPR:leaseAPR, leaseAnnualKm:leaseAnnualKm, province:province, incentivesSelected:incentivesSelected };
    var url = root + "/shopping_tools/bnp_to_friend.do?";
    var ampersand = false;
    for(var prop in obj) {
        if(obj[prop]) {
            if (ampersand) url += "&";
            else ampersand = true;
            url += prop + "=" + obj[prop];
        }
    }
    bnpPopUp(url);
}

function savePostalCode(postalCode) {
    $.get(root+"/changePostalCode.do?postalCode=" + escape(postalCode));
}

function flipComplete() {
	try {
		switch(nextScreen)
		{
			case "buildandprice":
	          if(isDeepLink) {
	            document.getElementById("bpHolder").innerHTML = "";
	            BuildBAndP();
	            isDeepLink = false;
	          }
			  //showApp();
			  break;    
			case "savedvehicles":
			case "compare":
	          if(!document.getElementById(nextScreen).innerHTML) loadBnpTabPage(nextScreen);
			  eval(nextScreen).apply(this);
			  break; 
		}
		showApp();
	}
	catch(e) {
		//alert("flipComplete() exception = " + e);
	}
}

function sendToFriendPopUp(newUrl)
{
	bnpPopUp(newUrl);
}

function bnpPopUp(url) {
    if(!bnpWin || bnpWin.closed) {
        bnpWin = window.open(url, "fordcapopup", "width=800,height=675,scrollbars=yes,location=no,menubar=no,toolbar=no,directories=no,resizable=no,status=yes");
    } else {
        bnpWin.location.href = url;
    }
    bnpWin.focus();
}

function goToUrl(newUrl) {
    if(newUrl.href) {
        newUrl = newUrl.href;
    }
    if (_dealerConnect == "false") {
    	_dealerConnect = false;
    }
    if(_dealerConnect) {
        if(newUrl.indexOf("?") == -1) newUrl += "?";
        else newUrl += "&";
        newUrl += "source=DC";
    }
	var t = setTimeout("delayURL('" + newUrl + "')", 500);
    return false;
}

function delayURL(url) {
	document.location.href = url;
}

function closeShell() {
    document.getElementById("transitionHolder").style.top = "0px";
	if(_context != "/lincoln"){
    	$("#msrp_legal").css("display","block");
   }
	
	hideAll();
	hideBnpLoader();
    bnpIsOpen = false;
    
	if(isSafari2) zoomOutComplete();
	else {
		try {
			document.getElementById("transition").zoomOut();
		} catch(e) {
			// Not sure why this happens
			//debug("transition zoomOut() exception = " + e);
			zoomOutComplete();
		}
	}
}

function loadBnpTab(link, params) {
    //bnpTimer.mark("Start loadBnpTab");
    var pos = {};
    var url;
    if(link.href) {
        url = link.href;
        pos.x = getX(link);
        pos.y = getY(link);
    } else {
        url = link;
        pos.x = 400;
        pos.y = 400;
    }
    loadBnpTabPage(params.section, url);
    OpenFlash(pos.x,pos.y,params);
    //bnpTimer.mark("End loadBnpTab");
    return false;
}

function loadBnpTabPage(section, url) {
	showBnpLoader();
    //bnpTimer.mark("Start loadBnpTabPage");
    if(!url) {
        if(section == "compare") url = root+"/vehicle_comparison.jsp";
        else if(section == "savedvehicles") {
        	var id = _customerVehicleId;
        	var vhclParam = (id) ? "&vehicleId=" + id : "";
        	url = root+"/garage/view.do?ajax=" + section + vhclParam;
        }
        else return;
    }
    if(url.indexOf("?") == -1) url += "?";
    else url+= "&";
    url += "timer=" + (new Date()).getTime();
    $("#" + section).load(url, null, eval(section+"Load"));
    //bnpTimer.mark("End loadBnpTabPage");
    hideBnpLoader();
}
function compareLoad() {
	// It's preferable to call showDefaultSelectionBox instead of getCompareVehicles
   // tryWhenAvailable("getCompareVehicles");
	
	// Calling from the loaded page instead to handle race conditions
   tryWhenAvailable("showDefaultSelelectionBox");

}

function showBnpLoader() {
	if (bnpIsOpen) showLoader("blackoutLoader");
}
function hideBnpLoader() {
	hideLoader();
}


var AnimateBnp = {
    //AnimateBnp.load("http://imageonthefly.autodatadirect.com/images/?IMG=CAB80FOC051B2101.png&HEIGHT=179&WIDTH=358&AUTOTRIM=1");
    //AnimateBnp.load("http://fordca/photos/buildandprice/colorized/358x179/4568/4568_032_D3.png");
    _id: "bnpAnimate",
    _image: {
        marginTop: 0,
        marginLeft: 0,
        top: 92,
        left: getX(document.getElementById("BAndP")) + 231,
        width: 358,
        height: 179,
        opacity: 2
    },
    load: function(imageUrl) {
        var start = {
            marginTop: -1 * AnimateBnp._image.top / 2,
            marginLeft: 400,
            top: AnimateBnp._image.top,
            left: AnimateBnp._image.left,
            width: AnimateBnp._image.width / 2,
            height: AnimateBnp._image.height / 2,
            opacity: 0
        };
        this._createImage(imageUrl, start, function() {
            AnimateBnp._animate(AnimateBnp._image);
        });
    },
    prepareUnload: function(imageUrl) {
        AnimateBnp._createImage(imageUrl, AnimateBnp._image, function() {
            alert("Tell flash the image is loaded");
        });
    },
    unload: function() {
        var finish = {
            marginTop: org.top / 2,
            marginLeft: -400,
            width: org.width * 1.5,
            height: org.height * 1.5,
            opacity: 0
        };
        // It's best not to use 'this' incase it's called in a callback (just the function is given)
        AnimateBnp._animate(finish, AnimateBnp.clear);
    },
    _createImage: function(imageUrl, attrs, onLoad) {
        var img = document.createElement("img");
        img.id = AnimateBnp._id;
        img.src = imageUrl;
        img.width = attrs.width;
        img.height = attrs.height;
        img.style.position = "absolute";
        img.style.zIndex = 5000;
        img.style.top = attrs.top + "px";
        img.style.left = attrs.left + "px";
        img.style.marginTop = attrs.marginTop + "px";
        img.style.marginLeft = attrs.marginLeft + "px";
        img.style.opacity = attrs.opacity;
        document.body.appendChild(img);
        
        var jimg = $(img);
        jimg.css("opacity", attrs.opacity);
        if(onLoad) jimg.load(onLoad);
    },
    _animate: function(finish, callback) {
        $(AnimateBnp._id).animate({marginTop:finish.marginTop+"px",marginLeft:finish.marginLeft+"px",width:finish.width+"px",height:finish.height+"px",opacity:finish.opacity},1500, null, callback);
        //animateBnp(true, "http://imageonthefly.autodatadirect.com/images/?IMG=CAB80FOC051B2101.png&HEIGHT=179&WIDTH=358&AUTOTRIM=1");
        //animateBnp(true, "http://fordca/photos/buildandprice/colorized/358x179/4568/4568_032_D3.png");
    },
    clear: function() {
        $(AnimateBnp._id).remove();
    }
}

/*
function animateBnp(load, imageName) {
    var org = {
        marginTop: 0,
        marginLeft: 0,
        top: 92,
        left: getX(document.getElementById("BAndP")) + 231,
        width: 358,
        height: 179,
        opacity: 2
    };
    var start;
    var finish;
    if(load) {
        start = {
            marginTop: -1 * org.top / 2,
            marginLeft: 400,
            top: org.top,
            left: org.left,
            width: org.width / 2,
            height: org.height / 2,
            opacity: 0
        };
        finish = org;
    } else {
        start = org;
        finish = {
            marginTop: org.top / 2,
            marginLeft: -400,
            width: org.width * 1.5,
            height: org.height * 1.5,
            opacity: 0
        };
    }
    
}
*/
function animateCompare(load, elem) {
	if(!useCompareAnimation) return;
    var img = $(elem);
    if(load) {
        img.css("opacity",0);
        img.load(function() {img.animate({opacity:2,marginLeft:"0px"},1500);});
    } else {
        img.animate({opacity:0,marginLeft:"-300px"},700);
    }
}