/* 
Main library for FiatCoUk
@updated 31/03/09:  Steve Smith     |   Refactored code to use MooTools API for brevity
                                        Removed getElementsByClass()
                                        Rename configureErrMsgPopup to configureModalPopup
                                        Added Comments
*/

/*
Used by the third party header to create absolute
urls for the openContactConsole() function 
*/
var webSiteUrl = '';

/*
Used by fixPNG to get element background image
*/
function returnBgImage(obj) {
    return obj.substring(5, obj.length - 2);
}

/*
Apply IE6 png transparency fix to a given object
Uses AlphaImageLoader and removes any existing image reference
*/
function fixPNG(imageObj) {
	var pngURL;
    if (imageObj.nodeName=="IMG" || imageObj.nodeName=="INPUT") {
        pngURL = imageObj.src;
        imageObj.runtimeStyle.backgroundImage = "none";
        imageObj.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + pngURL + "', sizingMethod='image')";
        imageObj.src = "/library/images/blank.gif";
        imageObj.style.visibility="visible";    
    } 
    else {
        pngURL = returnBgImage(imageObj.currentStyle.backgroundImage);
        if (pngURL != 'ne') {
            imageObj.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + pngURL + "',sizingMethod='scale')";
            imageObj.style.backgroundImage="none";
            imageObj.style.visibility="visible";
        }    
    }
}

/*
Apply IE6 png transparency fix to all elements with 'fixPNG' class
*/
function fixPNGs() {
    var pngs = $$(".fixPNG");
    for (var i = 0; i < pngs.length; i++) {
       fixPNG(pngs[i]);
    } 
}

/*
Attach function calls to onload event

window.addEvent('load', function(){
	if (typeof updateAnchors != "undefined") {
		updateAnchors();
	} 
	if (typeof setLogLinks != "undefined") {
		setLogLinks();
	}
    if(window.ie6) {
		fixPNGs();
	}
});
*/

/*
Used by skinButton()
Changes the text colour, attached to onmouseover event
of a skinned input element
*/
function hoverOver() {
    this.style.color ="#fff";
}

/*
Used by skinButton()
Changes the text colour, attached to onmouseout event
of a skinned input element
*/
function hoverOut() {
    this.style.color ="#ccc";
}

/*
Skins each button by wrapping the anchor in several divs
and attaching css classes and rollover events as necessary
*/
function skinButton(butt) {
    // default inputs for safari
    if(butt.nodeName=="INPUT" && window.khtml) {
        return;
    }
    else {
        // if already skinned ignore
        if (butt.parentNode.id != "skinnedButton") {
            var fragment= document.createDocumentFragment();
            var btnWrapper = document.createElement("div");
            btnWrapper.className="button";
            var btnBody = document.createElement("div");
            btnBody.className="body fixPNG";
            btnBody.id="skinnedButton";
       
            // append cloned element to container
            var btnTrigger = butt.cloneNode(true);
            btnBody.appendChild(btnTrigger);

            // input rollovers
            if(butt.nodeName=="INPUT") {
                btnTrigger.onmouseover = hoverOver;
                btnTrigger.onmouseout = hoverOut;
            }
  
            // left and right edges
            var btnRightEdge = document.createElement("div");
            btnRightEdge.className="rightEdge fixPNG";
            var btnLeftEdge = document.createElement("div");
            btnLeftEdge.className="leftEdge fixPNG";
            btnWrapper.appendChild(btnLeftEdge);
            btnWrapper.appendChild(btnBody);
            btnWrapper.appendChild(btnRightEdge);
    
            // add button to fragment
            fragment.appendChild(btnWrapper);
    
            // replace fragment with original
            butt.parentNode.replaceChild(fragment, butt);
        }
    }
}

/*
Calls skinButton function for each element with class of 'skinButton' 
*/
function skinButtons() {
    var buttons = $$(".skinButton");
    var staticInputs = $$(".button");

    for (var i = 0; i < buttons.length; i++) {
    	if (buttons[i] != null && buttons[i] != "undefined") {
    		skinButton(buttons[i]);
    	}
	}
	for (var n = 0; n < staticInputs.length; n++) {
		if (staticInputs[n] != null && staticInputs[n] != "undefined") {
			if (typeof (staticInputs[n].getElements('input')[0]) != "undefined") {
				staticInputs[n].getElements('input')[0].onmouseover = hoverOver;
				staticInputs[n].getElements('input')[0].onmouseout = hoverOut;
			}
       	}
	}
}

/*
Attached to the the endRequest event of the PageRequestManager instance 
*/
function onEndRequest(sender, args) {
  sIFRReplace();
  skinButtons();
  if($$('div.comparison') !== ''){
    addCompareEvents();
  }
}

/*
Used by .NET UpdatePanels to add a call to onEndRequest() on the endRequest event
of the PageRequestManager instance 
*/
function pageLoad() {
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (!prm.get_isInAsyncPostBack()) {
        prm.add_endRequest(onEndRequest);
    }
}

/*
Used by .NET UpdatePanels to remove the call to onEndRequest() on the endRequest event
of the PageRequestManager instance 
*/
function pageUnload() {
    Sys.WebForms.PageRequestManager.getInstance()
        .remove_endRequest(onEndRequest);
}

/*
Configure modal popup box, previously named 'configureErrMsgPopup'
Used to show important information in a styled modal box
E.g. 'Hear About It First' box on the right of /content/article.aspx
Called from FiatUpdates.ascx, UserAccountMyDetails.ascx & UserAccountMyFiatCare.ascx
*/
function configureModalPopup(sBoxSize){
    var ePopupBoxContainer = document.getElementById('errMsgPopupContainer');
    var ePopupBoxBackground = document.getElementById('errMsgPopupBackground');
    var ePopupBox = document.getElementById('errMsgPopup');
    var sTargetSize;
    var nPopupWidth;
    var nPopupHeight;
    var nBrowserWidth = document.body.offsetWidth;
    var nBrowserHeight = document.body.offsetHeight;
    var nBrowserViewWidth;
    var nBrowserViewHeight;
    if(window.innerWidth){
		nBrowserViewWidth = window.innerWidth;
	}
	else if(document.body.clientWidth) {
		nBrowserViewWidth = document.body.clientWidth;
	}
    if(window.innerHeight) {
		nBrowserViewHeight = window.innerHeight;
	} 
	else if(document.body.clientHeight) {
		nBrowserViewHeight = document.body.clientHeight;
	}
    
    switch(sBoxSize.toLowerCase()){
        case 'none':
            sTargetSize = 'errNonePopup';
            nPopupWidth = 700;
            nPopupHeight = 260;
        break;
        case 's':
            sTargetSize = 'err300Popup';
            nPopupWidth = 300;
            nPopupHeight = 260;
        break;
        case 'm':
            sTargetSize = 'err500Popup';
            nPopupWidth = 500;
            nPopupHeight = 260;
        break;
        case 'l':
            sTargetSize = 'err700Popup';
            nPopupWidth = 700;
            nPopupHeight = 260;
        break;
        case 'hide':
            sTargetSize = 'err500Popup errHidePopup';
            nPopupWidth = 500;
            nPopupHeight = 200;
        break;
        default:
            sTargetSize = 'err500Popup';
            nPopupWidth = 500;
            nPopupHeight = 260;
    }
    
    var IsContact = document.location.href.indexOf('contactconsole');
    ePopupBoxBackground.style.width = (nBrowserWidth) + 'px';
    ePopupBoxBackground.style.height = nBrowserHeight + 'px';
    ePopupBox.className = 'errMsgPopup ' + sTargetSize;
    ePopupBox.style.left = (nBrowserViewWidth/2)-(nPopupWidth/2) + 'px';
    var nCompare;
    if(window.pageYOffset){
        nCompare = ((nBrowserViewHeight/2)-(nPopupHeight/2))+window.pageYOffset;
    } else {
        nCompare = ((nBrowserViewHeight/3)-(nPopupHeight/2)+document.documentElement.scrollTop);
    }
    ePopupBox.style.top = nCompare + 'px';
    if(nCompare<=280){if(IsContact=='-1'){ePopupBox.style.top = '280px';} else {ePopupBox.style.top = '200px';}}
    ePopupBoxContainer.style.display = 'block';
    skinButtons();
    sIFRReplace();
}

/*
Used to hide a modal pop up that was generated using configureModalPopup()
*/
function closeErrMsgPopup(){
    var ePopupBoxContainer = document.getElementById('errMsgPopupContainer');
    ePopupBoxContainer.style.display = 'none';
}

/*
Used to create a cookie with the given values
*/
function createCookie(name,value,days) {
	var expires;
    
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else {
		expires = "";
	}
    document.cookie = name+"="+value+expires+"; path=/";
}

/*
Reads the value of a named cookie
*/
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;
}

/*
Erases a named cookie
*/
function eraseCookie(name) {
    createCookie(name,"",-1);
}

/*
Stores a cookie with the URL of a saved configured car
*/
function setCarConfigurationCookie(configUrl) {
    createCookie("savedCarConfiguration",configUrl);
}

/*
Returns a specification list for a window.open method call
*/
function buildWindowSpecificationString(width, height, displayTitleBar, displayLocationBar, displayStatusBar, displayScrollbars, displayMenuBar, isResizable) {
	specifications = "width=" + width + ", ";
	specifications += "height=" + height + ", ";
	specifications += "titlebar=" + displayTitleBar + ", ";
	specifications += "location=" + displayLocationBar + ", ";
	specifications += "status=" + displayStatusBar + ", ";
	specifications += "scrollbars=" + displayScrollbars + ", ";
	specifications += "menubar=" + displayMenuBar + ", ";
	specifications += "resizable=" + isResizable;
	
	return specifications;
}

/*
Adds extra height to IE7 popups to accomodate address bar
*/
function fixHeight(height) {
	var offset = 0;

	if (window.ie7) {
		offset = 30;
	}
	return parseInt(height, 10) + offset;
}

/*
Adds extra width to IE7 popups to accomodate address bar
*/
function fixWidth(width) {
	var offset = 0;

	if (window.ie7) {
		offset = 30;
	}
	return parseInt(width, 10) + offset;
}

function getSpecificationValue(value, defaultValue) {
	if(value === null || typeof(value) == "undefined") {
		value = defaultValue;
	}
	
	return value;
}

/*
Generic function for handling of popups
Usage: can be called with only non-default values - only mandatory argument is 'url', e.g.
	openPopup("/500Abarth/default.aspx"); 
		will use all default values
	openPopup("/500abarth/default.aspx", "100", "100", "yes", "yes", "yes", "yes", "yes", "yes", 0, 2);	
		will use given values
*/
function openPopup(url, width, height, displayTitleBar, displayLocationBar, displayStatusBar, displayScrollbars, displayMenuBar, isResizable, leftPosition, topPosition) {
	var defaultWidth = 575;
	var defaultHeight = 300;
	var name = "FiatPopUp";
	var defaultDisplayTitleBar = "no";
	var defaultDisplayLocationBar = "no";
	var defaultDisplayStatusBar = "no";
	var defaultDisplayScrollbars = "yes";
	var defaultDisplayMenuBar = "no";
	var defaultIsResizable = "yes";
	
	width = getSpecificationValue(width, defaultWidth);
	height = getSpecificationValue(height, defaultHeight);
	displayTitleBar = getSpecificationValue(displayTitleBar, defaultDisplayTitleBar);
	displayLocationBar = getSpecificationValue(displayLocationBar, defaultDisplayLocationBar);
	displayStatusBar = getSpecificationValue(displayStatusBar, defaultDisplayStatusBar);
	displayScrollbars = getSpecificationValue(displayScrollbars, defaultDisplayScrollbars);
	displayMenuBar = getSpecificationValue(displayMenuBar, defaultDisplayMenuBar);
	isResizable = getSpecificationValue(isResizable, defaultIsResizable);
	height = fixHeight(height);
	width = fixWidth(width);

	var specifications = buildWindowSpecificationString(width, height, displayTitleBar, displayLocationBar, displayStatusBar, displayScrollbars, displayMenuBar, isResizable);

	var newWindow = window.open(url, name, specifications);
	if (window.focus) { newWindow.focus() }
	return;
}

/*
If supported, opens page in openening window
else opens page in new window
*/
function openUrlInParent(url) {
	var targetWindow;
	try {
		targetWindow = window.open(url, window.opener);
	}
	catch(ex) {
		targetWindow = window.open(url);
	}
	targetWindow.focus();
	window.close();
}

/*
Close 'newWindow' window
*/
function closePopup() {
	if (typeof (newWindow) != "undefined" && newWindow != null) {
		newWindow.close();
	}
}

/*
Launches the contact console popup 
Note that webSiteUrl (global var set at top of file) may be set by thirdparty/header.aspx to 
provide an absolute url to contact console
*/
function openContactConsole(id, trackId, mediaCode) {
    var hashValue = currentHash; //window.location.hash.replace("#", "");
    var defaultMediaCode = '106';

    if (hashValue === '' || hashValue == null || typeof (hashValue) == 'undefined') {
    	hashValue = window.location.hash.replace("#", "");
    }

    if (mediaCode === '' || mediaCode == 'null' || typeof (mediaCode) == 'undefined') {
        mediaCode = defaultMediaCode;
    }

	switch(id) {
		case "book":
			openPopup(webSiteUrl + "/contactconsole/ArrangeTestDrive.aspx?eddb=true&mediaCode=" + mediaCode + '&hash=' + hashValue, "575", "685");
			break;
		case "configure":
			tc_log(trackId);
			window.location.href = webSiteUrl+"/Showroom/?id=14237#showroom/configurator/configurator_home";
			break;
	    case "termsconditions":
			openPopup(webSiteUrl+"/PicnicTerms/Default.aspx", "575", "685");
			break;
		case "privacy":
			openPopup(webSiteUrl+"/PicnicPrivacy/", "575", "685");
			break;
		case "contactdealer":
			openPopup(webSiteUrl + "/contactconsole/ContactDealer.aspx?&hash=" + hashValue, "575", "685");
			break;
		case "500byDiesel":
			openPopup(webSiteUrl+"/contactconsole/InfoRequest500Diesel.aspx", "560", "752");
			break;
		case "book500byDIESEL": 
			openPopup(webSiteUrl+"/contactconsole/ArrangeTestDrive500ByDiesel.aspx", "555", "590");
			break;
		default:
			openPopup(webSiteUrl + "/contactconsole/requestbrochure.aspx?mediaCode=" + mediaCode + '&hash=' + hashValue, "575", "600");
			break;
    }

    if (trackId !== '')  {
        tc_log(trackId);
    }
        
    return false;
}

/*
Launches contact dealer popup
*/
function openContactDealer(modelCode) {
    window.open(webSiteUrl+"/contactconsole/ContactDealer.aspx?modelCode=" + modelCode,'name', 'location=0,status=0,scrollbars=1,height=685,width=575,resizable=1');
    return false;
}

/*
Redirects browser to given url and logs given tracking code
*/
function navToUrl(url, trackingCode) {
    if (url !== '')  {
        window.location.href = url;
    }
    if (trackingCode !== '') {
        tc_log(trackingCode);
    }
    return false;   
}

/*
Returns the rollover filename for a given filename
e.g. imageName.gif will return imageName<rolloverFileIdentifier>.gif
@param fileName: the original filename
@param rolloverFileIdentifier: the identifying text for a rollover, e.g. '_over'
*/
function getMouseOverFileName(fileName, rolloverFileIdentifier) {
    var fileNameWithoutExtension;
    var extension;
    var positionOfLastPeriod = fileName.lastIndexOf(".");
    
    fileNameWithoutExtension = fileName.substr(0, positionOfLastPeriod);
    extension = fileName.substr(positionOfLastPeriod);
    
    return fileNameWithoutExtension + rolloverFileIdentifier + extension;
}

/*
Returns the given fileName with the rolloverFileIdentifier text removed
e.g. imageName_over.gif will return imageName.gif
@param fileName: the filename
@param rolloverFileIdentifier: the identifying text for a rollover, e.g. '_over'
*/
function getMouseOutFileName(fileName, rolloverFileIdentifier) {
    return fileName.replace(rolloverFileIdentifier, "");
}

/*
Generic function for handling of image button rollovers
*/
function handleRollovers() {
    var rolloverClassName = ".rollover";
    var rolloverFileIdentifier = "-over";
    
    var collectionOfElements = $$(rolloverClassName);
    for(var i = 0; i < collectionOfElements.length; i++){
        collectionOfElements[i].addEvent("mouseover", function(event) {
            this.src = getMouseOverFileName(this.src, rolloverFileIdentifier);
        });
        collectionOfElements[i].addEvent("mouseout", function(event) {
            this.src = getMouseOutFileName(this.src, rolloverFileIdentifier);
        });
    }
}

/* 
500 model redirect method
Notes: Used by the Fiat 500 model specification pages. Called on change of the model choice drop down. 
@param modelIndex: The model index passed
*/ 
function redirectToModelSpecificationPage(modelIndex) {
    modelIndex = parseInt(modelIndex, 10);
    switch (modelIndex) {
        case 1 :
        window.location = "/Showroom/Fiat500/Pop12.aspx";
        break;
        case 2 :
        window.location = "/Showroom/Fiat500/Pop13MJT.aspx";
        break;
        case 3 :
        window.location = "/Showroom/Fiat500/Pop14.aspx";
        break;
        case 4 :
        window.location = "/Showroom/Fiat500/Lounge12.aspx";
        break;
        case 5 :
        window.location = "/Showroom/Fiat500/Lounge13MJT.aspx";
        break;
        case 6 :
        window.location = "/Showroom/Fiat500/Lounge14.aspx";
        break;
        case 7 :
        window.location = "/Showroom/Fiat500/Sport12.aspx";
        break;
        case 8 :
        window.location = "/Showroom/Fiat500/Sport13MJT.aspx";
        break;
        case 9 :
        window.location = "/Showroom/Fiat500/Sport14.aspx";
        break;
    }
}

//These buttons perform all call the following Javascript function 'openSpecialWindow' and pass in either:
//BOOK , REQUEST or CONFIGURE

function openSpecialWindow(sType){
    //alert(sType);
    switch (sType) {
    case 'BOOK': 
        //window.location = "http://www.fiat.co.uk/contactconsole/ArrangeTestDrive.aspx?eddb=true&mediaCode=106&hash=showroom/home";
        window.open("http://www.fiat.co.uk/contactconsole/ArrangeTestDrive.aspx?eddb=true&mediaCode=106&hash=showroom/home",sType,'location=0,status=0,scrollbars=1,height=685,width=575,resizable=1');
        break;
    case 'REQUEST':
        //window.location = "http://www.fiat.co.uk/contactconsole/requestbrochure.aspx?mediaCode=106&hash=showroom/home";
        window.open("http://www.fiat.co.uk/contactconsole/requestbrochure.aspx?mediaCode=106&hash=showroom/home",sType,'location=0,status=0,scrollbars=1,height=685,width=575,resizable=1');
        break;
    case 'CONFIGURE':
        //window.location = "http://www.fiat.co.uk/Showroom/#showroom/configurator/configurator_home";
        window.open("http://www.fiat.co.uk/Showroom/#showroom/configurator/configurator_home",sType,'location=0,status=0,scrollbars=1,height=610,width=1010,resizable=1');
        break;
    default: alert('error');
    }
}