////////////////////////////////////////////////////////////////
// Last Modified: 11-30-2006
// Modifier: Mike Stegmann
////////////////////////////////////////////////////////////////

//***************************** General methods ****************************************//
function getSelectedValue(select)
{
    var val = select.value;
    //alert('val=' + val);
    if(val == undefined)
    {
         val = select.options[select.selectedIndex].value;
    }
    return val;
}
function getSelectedText(select)
{
    var val = select.text;
    if(val == undefined)
    {
        val = select.options[select.selectedIndex].text;
    }
    return val;
}
function addOption(selectbox,text,value )
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}
function bindDictionaryToSelectBox(selectbox, dictionary)
{
    for(var index = 0; index < dictionary.length; index++)
    {
        addOption(selectbox, dictionary[index].Name, dictionary[index].Value);
    }
}
function bindListToSelectBox(selectbox, list)
{
    for(var index = 0; index < list.length; index++)
    {
        addOption(selectbox, list[index], list[index]);
    }
}
function getAspForm()
{
    var aspForm = document.forms['aspnetForm'];
    if(!aspForm)
    {
        aspForm = document.aspnetForm;
    }
    return aspForm;
}
function setToLoadingSelectBox(selectbox, loading)
{
    //alert('setToLoadingSelectBox(' + selectbox + ',' + loading + ')');
    selectbox.options.length = 0;
    if(loading)
    {
        addOption(selectbox, "Loading...", "0");
    }
    selectbox.disabled = true;
}
//**************************************************************************************//

// Custom event-binder that allows for concurrent event implementations.
function BindEvent(bindingObject, bindingEvent, boundDelegate)
{
	try
	{
		var bindingEventValue = new String(bindingEvent);
		if (bindingObject.attachEvent)
		{
			bindingObject.attachEvent(bindingEvent, boundDelegate);
		}
		else if (bindingObject.addEventListener)
		{
			bindingEventValue = bindingEventValue.toLowerCase().replace("on", "");
			bindingObject.addEventListener(bindingEventValue, boundDelegate, false);
		}
	} catch (e) {}
}

// Create a DHTML layer
function createLayer(name, left, top, width, height, visible, content, bg) {
	  var layer;
	  if (document.layers) {
	    document.writeln('<layer name="' + name + '" left=' + left + ' top=' + top + ' width=' + width + ' height=' + height +  ' visibility=' + (visible ? '"show"' : '"hide"') + ' bgcolor=' + bg + '>');
	    document.writeln(content);
	    document.writeln('</layer>');
	    layer = getLayer(name);
	    layer.width = width;
	    layer.height = height;
	  }
	
	  if (document.all) {
	    document.writeln('<div id="' + name + '" style="background-color: '+ bg +'; position:absolute; overflow:none; left:' + left + 'px; top:' + top + 'px; width:' + width + 'px; height:' + height + 'px;' + ' visibility:' + (visible ? 'visible;' : 'hidden;') +  '">');
	    document.writeln(content);
	    document.writeln('</div>');
	  }
		
	  clipLayer(name, 0, 0, width, height);
}

// get the layer object called "name"
function getLayer(name) {
	  if (document.layers)
	    return(document.layers[name]);
	  else if (document.all) {
	  	if ( eval('document.all.' + name) != null) {
		    layer = eval('document.all.' + name + '.style');
		    return(layer);
		} else
			return(null);
	  }
	  else
	    return(null);
}

// move layer to x,y
function moveLayer(name, x, y) {		
  	var layer = getLayer(name);		
	if (layer != null) {
	  	if (document.layers)
    		layer.moveTo(x, y);
	  	if (document.all) {
    		layer.left = x;
   			layer.top  = y;
	  	}
	}
}

// toggle layer to invisible
function hideLayer(name) {		
  	var layer = getLayer(name);		
	if (layer != null) {
	  	if (document.layers)
    		layer.visibility = "hide";
	  	if (document.all)
   			 layer.visibility = "hidden";
	}
}

// toggle layer to visible
function showLayer(name) {		
  	var layer = getLayer(name);		
	if (layer != null) {
	  	if (document.layers)
    		layer.visibility = "show";
	  	if (document.all) 
   		 layer.visibility = "visible";
	}
}

// clip layer display to clipleft, cliptip, clipright, clipbottom
function clipLayer(name, clipleft, cliptop, clipright, clipbottom) {		
	  var layer = getLayer(name);		
	  if (layer != null) {
		  if (document.layers) {
			    layer.clip.left   = clipleft;
			    layer.clip.top    = cliptop;
		    	layer.clip.right  = clipright;
			    layer.clip.bottom = clipbottom;
		  }
		  if (document.all)
			    layer.clip = 'rect(' + cliptop + ' ' +  clipright + ' ' + clipbottom + ' ' + clipleft +')';
	  }
}

function na_preload_img()
{ 

    var img_list = na_preload_img.arguments;

    if (document.preloadlist == null) 

    document.preloadlist = new Array();

    var top = document.preloadlist.length;

    for (var i=0; i < img_list.length-1; i++) {

        document.preloadlist[top+i] = new Image;

        document.preloadlist[top+i].src = img_list[i+1];
    } 
}

function gotoOrder(name){
	var myCatName = name;
	var myName = "CatalogRequestWindow";
	var myUrl = urlMatch +  "/store/commerce.shop?pageType=catrequest&catName=" + myCatName;
	//alert("myURL =" + myUrl);
	if(bEcom == "false"){
		myUrl = urlMatch +  "/flashdemo/order2.htm?catName=" + myCatName;
		popWin = window.open(myUrl, myName, "width=500, height=400, location=no, menubar=no, status=no, toolbar=no, scrollbars=no, resizable=no"); 
	}else if(bEcom == "b2clite"){
		myUrl = urlMatch +  "/contactus.htm?catName=" + myCatName;
		window.opener.location = myUrl;
	}
	else{
		popWin = window.open(myUrl, myName, "width=500, height=400, location=no, menubar=no, status=no, toolbar=no, scrollbars=no, resizable=no"); 
	}
}

function selectCatalog(){
if (document.getElementById('compCatSelectBox').value){
var newId=document.getElementById('compCatSelectBox').value;
window.location='catalogAsset.htm?catalogId=' + newId;
}
}

function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=502,height=425,left = 257,top = 179');");
}
var currentTabIndex ='1';

function selectContainer(containerId, tabObject){
	if (containerId !== currentTabIndex){
		var currentContainer = document.getElementById("container_"+currentTabIndex );
		var newContainer = document.getElementById("container_"+containerId);
		var newTab = tabObject;
		var currentTab = document.getElementById("selector_"+currentTabIndex );
		currentContainer.className = extractSelected(currentContainer.className);
		newContainer.className = insertSelected(newContainer.className);
		currentTab.className = extractSelected(currentTab.className);
		newTab.className = insertSelected(newTab.className);
		currentTabIndex = containerId;
	}
}
function extractSelected(className){
	var classNameNewLength = className.length -9;
	var newClassName = className.substr(0, classNameNewLength);
	return newClassName
}
function insertSelected(className){
	var newClassName = className + "_selected";
	return newClassName
}

function setRating(rating)
{
    var ratingInput = document.getElementById('rating');
    ratingInput.value = rating;
}

////////////////////////////// AFLAX FUNCTIONALITY //////////////////////////////////
function setHtml(targetId, html)
{
	var target = document.getElementById(targetId);
	if(target)
	{
		target.innerHTML = html;
	}
}
function createRequestObject() {
	try{
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
	}catch(e){
		//alert('error: ' + e);
		return new Object();
	}
}

var http = createRequestObject();

//------------------------------------ Tire Fitment Guide Ajax -------------------------------------------------//

var vehicleHttp = createRequestObject();

var IDMap = new Object();

var TFG = new Object();
TFG.OnRequestAQuoteClick = function()
{
    //alert('no handler has been assigned');
}

function getServerControl(clientName)
{
    //alert('getServerControl(' + clientName + ')');
    var id = IDMap[clientName];
    //alert('id: ' + id);
    var control = document.getElementById(id);
    //alert('control: ' + control);
    return control;
}

function enableSBVSubmit()
{
    var submit = getServerControl('btnSearchByVehicle');
    if(submit)
    {
        submit.disabled = false;
    }
}
function pauseSizes(loading)
{
    // Pause sizes list box
    var sizes = getServerControl('lstSizes');
    setToLoadingSelectBox(sizes, loading);
    // Disable "Go" button
    var submit = getServerControl('btnSearchByVehicle');
    if(submit)
    {
        submit.disabled = true;
    }
}
function pauseStyles(loading)
{
    // Pause styles drop-down
    var styles = getServerControl('cmbStyles');
    //alert('styles=' + styles);
    setToLoadingSelectBox(styles, loading);
    // Disable dependents
    pauseSizes(false);
}
function pauseModels(loading)
{
    // Pause models drop-down
    var models = getServerControl('cmbModels');
    //alert('models=' + models);
    setToLoadingSelectBox(models, loading);    
    // Disable dependents
    pauseStyles(false);
}
function pauseMakes(loading)
{
    // Pause makes drop-down
    var makes = getServerControl('cmbMakes');
    //alert('makes=' + makes);
    setToLoadingSelectBox(makes, loading);
    // Disable dependents
    pauseModels(false);
}
function pauseYears()
{
    // Pause years drop-down
    var years = getServerControl('cmbYears');
    //alert('years=' + years);
    setToLoadingSelectBox(years, true);
    // Disable dependents
    pauseMakes(false);
}
////////////////////// Search By Vehicle //////////////////////////////////////

//------------ Initial Years Loading ------------------//
function handleVehicleYearsInit()
{
    if(vehicleHttp.readyState == 4)
    {
        //alert('readyState=' + vehicleHttp.readyState);
        var response = vehicleHttp.responseXML;
        var root = response.documentElement;
        var content = root.firstChild.nodeValue;
        eval("var yearData = " + content + ";");
        var list = yearData.list;
        //alert('list.length=' + list.length);
        var years = getServerControl('cmbYears');
        //alert('years: ' + years);
        years.options.length = 0;
        addOption(years, "Pick a Year", "0");
        bindListToSelectBox(years, list);
        years.disabled = false;
    }
}

function requestVehicleYears()
{
    pauseYears();
    vehicleHttp.open('get', 'services/TireFitmentGuide.asmx/GetYearsJSON');
    vehicleHttp.onreadystatechange = handleVehicleYearsInit;
    vehicleHttp.send(null);
}
//-----------------------------------------------------//

//------------ On Years Selection ---------------------//
function handleTFGYearSelectResponse()
{
    if(vehicleHttp.readyState == 4)
    {
        //alert('vehicleHttp.readyState=' + vehicleHttp.readyState);
        var response = vehicleHttp.responseXML;
        var root = response.documentElement;
        var content = root.firstChild.nodeValue;
        eval("var tfgData = " + content + ";");
        var list = tfgData.list;
        var makes = getServerControl('cmbMakes');
        makes.options.length = 0;
        addOption(makes,'Pick a Make','0');
        bindDictionaryToSelectBox(makes, list);
        makes.disabled = false;
    }
}

function requestVehicleMakes(selectbox)
{
    //alert('requestVehicleMakes(' + selectbox + ')');
    // Retrieve year
    var year = getSelectedValue(selectbox);
    //alert('year=' + year);
    pauseMakes(true);
    // Send Request
    //alert('paused makes');
    vehicleHttp.open('GET', 'services/TireFitmentGuide.asmx/GetMakesJSON?year=' + year);
    vehicleHttp.onreadystatechange = handleTFGYearSelectResponse;
    vehicleHttp.send(null);
}
//----------------------------------------------//

//------------ On Makes Selection ---------------------//
function handleTFGMakeSelectResponse()
{
    if(vehicleHttp.readyState == 4)
    {
        //alert('vehicleHttp.readyState=' + vehicleHttp.readyState);
        var response = vehicleHttp.responseXML;
        var root = response.documentElement;
        var content = root.firstChild.nodeValue;
        eval("var tfgData = " + content + ";");
        var list = tfgData.list;
        var models = getServerControl('cmbModels');
        models.options.length = 0;
        addOption(models,'Pick a Model','0');
        bindDictionaryToSelectBox(models, list);
        models.disabled = false;
    }
}

function requestVehicleModels(selectbox)
{
    //alert('requestVehicleModels(' + selectbox + ')');
    // Retrieve makeId
    var makeId = getSelectedValue(selectbox);
    //alert('makeId=' + makeId);
    pauseModels(true);
    // Send Request
    vehicleHttp.open('GET', 'services/TireFitmentGuide.asmx/GetModelsJSON?makeId=' + makeId);
    vehicleHttp.onreadystatechange = handleTFGMakeSelectResponse;
    vehicleHttp.send(null);
}
//----------------------------------------------//

//------------ On Models Selection ---------------------//
function handleTFGModelSelectResponse()
{
    if(vehicleHttp.readyState == 4)
    {
        //alert('vehicleHttp.readyState=' + vehicleHttp.readyState);
        var response = vehicleHttp.responseXML;
        var root = response.documentElement;
        var content = root.firstChild.nodeValue;
        eval("var tfgData = " + content + ";");
        var list = tfgData.list;
        var styles = getServerControl('cmbStyles');
        styles.options.length = 0;
        addOption(styles,'Pick a Style','0');
        bindDictionaryToSelectBox(styles, list);
        styles.disabled = false;
    }
}

function requestVehicleStyles(selectbox)
{
    //alert('requestVehicleStyles(' + selectbox + ')');
    // Retrieve modelId
    var modelId = getSelectedValue(selectbox);
    //alert('modelId=' + modelId);
    pauseStyles(true);
    // Send Request
    vehicleHttp.open('GET', 'services/TireFitmentGuide.asmx/GetStylesJSON?modelId=' + modelId);
    vehicleHttp.onreadystatechange = handleTFGModelSelectResponse;
    vehicleHttp.send(null);
}
//----------------------------------------------//

//------------ On Styles Selection ---------------------//
var tireFitmentGuideTireSizeInfo = null;
var tireFitmentGuideTireSizeInfoIndex = 0;
function handleTFGStyleSelectResponse()
{
    if(vehicleHttp.readyState == 4)
    {
        //alert('vehicleHttp.readyState=' + vehicleHttp.readyState);
        var response = vehicleHttp.responseXML;
        var root = response.documentElement;
        var content = root.firstChild.nodeValue;
        //alert('content: ' + content);
        eval("var tfgData = " + content + ";");
        var list = tfgData.list;
        tireFitmentGuideTireSizeInfo = list;
        var sizes = getServerControl('lstSizes');
        sizes.options.length = 0;
        bindDictionaryToSelectBox(sizes, list);
        if(sizes.length>0) {
			sizes.selectedIndex = 0;
			getTFGTireSizeAtIndex(0);
			requestSubmitUrl(sizes);
		}
        sizes.disabled = false;
    }
}
function getTFGTireSizeAtIndex(index){
	var width = getServerControl('cmbWidth');
	if(width!=null && tireFitmentGuideTireSizeInfo!=null && tireFitmentGuideTireSizeInfo.length>index){
		tireFitmentGuideTireSizeInfoIndex = index;
		selectOptionValue(width, tireFitmentGuideTireSizeInfo[index].Width);
		requestHeights(width);
	}
}

function selectOptionValue(selectCtrl, value){
	if(value!=null && value!=""){
		for(var index=0; index < selectCtrl.options.length; index++){
			if(selectCtrl.options[index].value==value){
				selectCtrl.selectedIndex = index;
			}
		}
	} else {
		selectCtrl.selectedIndex = 0;
	}
}

function requestSearchResults(selectbox)
{
    //alert('requestSearchResults(' + selectbox + ')');
    // Retrieve styleId
    var styleId = getSelectedValue(selectbox);
    //alert('styleId=' + styleId);
    pauseSizes(true);
    // Send Request
    vehicleHttp.open('GET', 'services/TireFitmentGuide.asmx/GetTireSizesJSON?styleId=' + styleId);
    vehicleHttp.onreadystatechange = handleTFGStyleSelectResponse;
    vehicleHttp.send(null);
}
//----------------------------------------------//

//--------------- On Size Selection ----------------//
function handleTFGSizeSelectionResponse()
{
    if(vehicleHttp.readyState == 4)
    {
        //alert('vehicleHttp.readyState=' + vehicleHttp.readyState);
        var response = vehicleHttp.responseXML;
        //alert('response=' + response);
        var root = response.documentElement;
        //alert('root=' + root);
        var content = root.firstChild.nodeValue;
        //alert('content=' + content);
        var submit = getServerControl('btnRequestAQuote');
        //alert('submit=' + submit);
        if(response && submit)
        {
            //submit.value = 'Request a Quote';
            submit.disabled = false;
            TFG.OnRequestAQuoteClick = function()
            {
                //alert('TFG.OnRequestAQuoteClick(): ' + content);
                eval(content);
            }
        }
    }
}

function requestSubmitUrl(selectbox)
{
    var submit = getServerControl('btnSearchByVehicle');
    if(submit)
    {
        submit.disabled = false;
    }
    else
    {
        submit = getServerControl('btnRequestAQuote');
        if(submit)
        {
            //submit.value = 'Loading...';
            submit.disabled = true;
            //alert('requestSubmitUrl(' + selectbox + ')');
            // Retrieve year
            var yearBox = getServerControl('cmbYears');
            var year = (yearBox) ? getSelectedText(yearBox) : '';
            //alert('year=' + year);
            // Retrieve make
            var makeBox = getServerControl('cmbMakes');
            var make = (makeBox) ? getSelectedText(makeBox) : '';
            //alert('make=' + make);
            // Retrieve model
            var modelBox = getServerControl('cmbModels');
            var model = (modelBox) ? getSelectedText(modelBox) : '';
            //alert('model=' + model);
            // Retrieve style
            var styleBox = getServerControl('cmbStyles');
            var style = (styleBox) ? getSelectedText(styleBox) : '';
            //alert('style=' + style);
            // Retrieve styleId
            var styleId = (styleBox) ? getSelectedValue(styleBox) : '';
            //alert('styleId=' + styleId);
            // Retrieve size
            var size = getSelectedValue(selectbox);
            //alert('size=' + size);
            // Send Request
            var path = 'services/TireFitmentGuide.asmx/GetSubmitUrl?productListPage=TireFitmentProductList.htm&styleId=' + styleId
                                     + '&size=' + size
                                     + '&year=' + year
                                     + '&make=' + escape(make)
                                     + '&model=' + escape(model)
                                     + '&style=' + escape(style);
            //alert('path=' + path);
            vehicleHttp.open('GET', path);
            vehicleHttp.onreadystatechange = handleTFGSizeSelectionResponse;
            vehicleHttp.send(null);
        }
    }
}
//--------------------------------------------------//
var knownSizeHttp = createRequestObject();

function test_searchByKnownSize(){
	var width = getServerControl('cmbWidth');
	var height = getServerControl('cmbHeight');
	var diameter = getServerControl('cmbDiameter');
	if((width!=null && height!=null && diameter!=null) && (width.value=="0" || diameter.value=="0")){
		alert("Please select a tire size before searching");
		return false;
	}
	return true;
}

function test_searchByVehicle(){
	var sizes = getServerControl('lstSizes');
	if(sizes!=null && sizes.selectedValue==""){
		alert("Please select a tire size before searching");
		return false;
	}
	return true;
}


function pauseDiameters(loading)
{
    var diameters = getServerControl('cmbDiameter');
    //alert('diameters: ' + diameters);
    setToLoadingSelectBox(diameters, loading);
    var btnSubmit = getServerControl('btnSearchByKnownSize');
    //alert('btnSubmit: ' + btnSubmit);
}
function pauseHeights(loading)
{
    var heights = getServerControl('cmbHeight');
    setToLoadingSelectBox(heights, loading);
    pauseDiameters(false);
}

//------------ On Width Selection ---------------------//
function handleTFGWidthSelectResponse()
{
    if(knownSizeHttp.readyState == 4)
    {
        //alert('knownSizeHttp.readyState=' + knownSizeHttp.readyState);
        var response = knownSizeHttp.responseXML;
        var root = (response!=null) ? response.documentElement : null;
        var content = (response!=null && root!=null) ? root.firstChild.nodeValue : '{ "list":[ "" ] }';
        //alert('content: ' + content);
        eval("var tfgData = " + content + ";");
        var list = tfgData.list;
        var heights = getServerControl('cmbHeight');
        heights.options.length = 0;
        bindListToSelectBox(heights, list);
        heights.disabled = false;
		if(heights!=null && tireFitmentGuideTireSizeInfo!=null && tireFitmentGuideTireSizeInfo.length>tireFitmentGuideTireSizeInfoIndex){
			selectOptionValue(heights, tireFitmentGuideTireSizeInfo[tireFitmentGuideTireSizeInfoIndex].Height);
		}
        requestDiameters(heights);
        var submit = getServerControl('btnSearchByKnownSize');
        submit.disabled = (response!=null && root!=null) ? false : true;
    }
}

function requestHeights(selectbox)
{
    //alert('requestHeights(' + selectbox + ')');
    // Retrieve width
    var width = getSelectedValue(selectbox);
    //alert('width=' + width);
    pauseHeights(true);
    // Send Request
    if(selectbox.Value!=""){
		knownSizeHttp.open('GET', 'services/TireFitmentGuide.asmx/GetTireHeightsJSON?width=' + width);
		knownSizeHttp.onreadystatechange = handleTFGWidthSelectResponse;
		knownSizeHttp.send(null);
	} else {
		handleTFGWidthSelectResponse();
	}
}
//----------------------------------------------//

//------------ On Height Selection ---------------------//
function handleTFGHeightSelectResponse()
{
    if(knownSizeHttp.readyState == 4)
    {
        //alert('vehicleHttp.readyState=' + vehicleHttp.readyState);
        var response = knownSizeHttp.responseXML;
        var root = (response!=null) ? response.documentElement : null;
        var content = (response!=null && root!=null) ? root.firstChild.nodeValue : '{ "list":[ "" ] }';
        //alert('content: ' + content);
        eval("var tfgData = " + content + ";");
        var list = tfgData.list;
        var diameters = getServerControl('cmbDiameter');
        diameters.options.length = 0;
        bindListToSelectBox(diameters, list);
        diameters.disabled = false;
        if(diameters!=null && tireFitmentGuideTireSizeInfo!=null && tireFitmentGuideTireSizeInfo.length>tireFitmentGuideTireSizeInfoIndex){
			selectOptionValue(diameters, tireFitmentGuideTireSizeInfo[tireFitmentGuideTireSizeInfoIndex].Diameter);
		}
    }
}

function requestDiameters(selectbox)
{
    //alert('requestDiameters(' + selectbox + ')');
    // Retrieve width
    var width = getSelectedValue(getServerControl('cmbWidth'));
    //alert('width=' + width);
    // Retrieve height
    var height = getSelectedValue(selectbox);
    //alert('height=' + height);
    pauseDiameters(true);
    // Send Request
    if(selectbox.Value!=""){
		knownSizeHttp.open('GET', 'services/TireFitmentGuide.asmx/GetTireDiametersJSON?width=' + width + '&height=' + height);
		knownSizeHttp.onreadystatechange = handleTFGHeightSelectResponse;
		knownSizeHttp.send(null);
    } else {
		handleTFGHeightSelectResponse();
    }
}
//----------------------------------------------//

//------------------- TFG Unload ---------------------------//

function resetTFG(){
    var yearBox = getServerControl('cmbYears');
    if(yearBox){ 
		yearBox.selectedIndex = 0; 
        var sizes = getServerControl('lstSizes');
        if(sizes){ sizes.options.length = 0; }
        var makeBox = getServerControl('cmbMakes');
        if(makeBox) makeBox.options.length = 0;
        var modelBox = getServerControl('cmbModels');
        if(modelBox) modelBox.options.length = 0;
        var styleBox = getServerControl('cmbStyles');
        if(styleBox) styleBox.options.length = 0;
        var submit = getServerControl('btnSearchByVehicle');
        if(submit) submit.disabled = true;
	}
    var width = getServerControl('cmbWidth');
    if(width){
        width.selectedIndex = 0;
        var heights = getServerControl('cmbHeight');
        if(heights) heights.selectedIndex = 0;
        var diameters = getServerControl('cmbDiameter');
        if(diameters) diameters.selectedIndex = 0;
    }
}

function onWindowLoad(){
    sortables_init();
    resetTFG();
}

//----------------------------------------------------------//
////////////////////////////////////////////////////////////

//--------------------------------------------------------------------------------------------------------------//

//------------------------------------ Showcase New Equipment Ajax ---------------------------------------------//
function handleHttpResponse() {
    if(http.readyState == 4){
        //alert('handleHttpResponse(): readyState=' + http.readyState);
        var response = http.responseXML;
        //alert('response: ' + response);
        var rootNode = response.documentElement;
        //alert('rootNode: ' + rootNode);
        var targetId = rootNode.getAttribute("targetId");
        //alert('targetId: ' + targetId);
        var fragments = rootNode.childNodes;
        //alert('fragments: ' + fragments);
        var content = '';
        if(fragments.length > 1){
            for(var i=0; i < fragments.length; i++){
                if(fragments[i].nodeName == 'fragment'){
                    content += fragments[i].firstChild.nodeValue;
                    //alert('fragment: ' + fragments[i].firstChild.nodeValue);
                }
            }
            //alert('fragmented content: ' + content);
        }else{
            content = rootNode.firstChild.nodeValue;
            //alert('non-fragmented content: ' + content);
        }
        //alert('content: ' + content);
        //alert('contentLength: ' + content.length);
        if(targetId && content) {
            var target = document.getElementById(targetId);
            if(target)
            {
                target.innerHTML = content;
                //alert('innerHTML: ' + target.innerHTML);
            }
            //document.getElementById(targetId).innerHTML = content;
        }
    }
}

function sndReq(targetId, service, productId, action) {
    //alert('sndReq(' + targetId + ',' + service + ',' + productId + ',' + action + ')');
    http.open('get', service + '?targetId='+targetId+'&productId='+productId+'&actionId='+action);
    http.onreadystatechange = handleHttpResponse;
    http.send(null);
}
//--------------------------------------------------------------------------------------------------------------------------//

//------------------------------------ Showcase Used Equipment Ajax ---------------------------------------------//
function handleUsedHttpResponse() {
    if(http.readyState == 4){
        var response = http.responseXML;
        var rootNode = response.documentElement;
        var targetId = rootNode.getAttribute("targetId");
        var content = rootNode.firstChild.nodeValue;
        if(targetId && content) {
            document.getElementById(targetId).innerHTML = content;
		sortables_init();
        }
    }
}

//----------------------------------- Review List Ajax ---------------------------------------------------------------//
function sndReviewReq(targetId, service, productId) {
    http.open('get', service + '?targetId='+targetId+'&productId='+productId);
    http.onreadystatechange = handleHttpResponse;
    http.send(null);
}


function sendRequestForUsedEquipmentList(service) {
	http.open('get', service);
    http.onreadystatechange = handleUsedHttpResponse;
    http.send(null);
}
//--------------------------------------------------------------------------------------------------------------------------//

//addEvent(window, "load", sortables_init)
addEvent(window, "load", onWindowLoad);
///////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////// TABLE SORTING FUNCTIONALITY /////////////////////////////////////

var SORT_COLUMN_INDEX;


function sortables_init() {
	var sortTblId = 'ecms_sortableTblCtl';
	thisTbl = document.getElementById(sortTblId);
      if(thisTbl){   
	ts_makeSortable(thisTbl);
	}
}

function ts_makeSortable(table) {
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;
    
    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i=0;i<firstRow.cells.length;i++) {
        var cell = firstRow.cells[i];
        var txt = cell.innerHTML;
	  if(txt !='&nbsp;'){
        cell.innerHTML = '<a href="#" class="ecms_sortableTblCtlSelector" onclick="ts_resortTable(this);return false;">'+txt+'<span class="ecms_sortableTblCtlDirection"><img src="media/arrowNull.gif" /></span></a>';
	}
    }
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function ts_resortTable(lnk) {
    // get the span
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var spantext = ts_getInnerText(span);
    var td = lnk.parentNode;
    var column = td.cellIndex;
    var table = getParent(td,'TABLE');
    
    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = ts_getInnerText(table.rows[1].cells[column]);
    sortfn = ts_sort_caseinsensitive;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/[£$]/)) sortfn = ts_sort_currency;
    if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
    SORT_COLUMN_INDEX = column;
    var firstRow = new Array();
    var newRows = new Array();
    for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
    for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }

    newRows.sort(sortfn);

   if (span.getAttribute("sortdir") == 'down') {
        ARROW = '<img src="media/downArrowBlack.gif" />';
        newRows.reverse();
        span.setAttribute('sortdir','up');
    } else {
       ARROW = '<img src="media/upArrowBlack.gif" />';
      span.setAttribute('sortdir','down');
    }
    
    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
    // do sortbottom rows only
    for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}
    
    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'ecms_sortableTblCtlDirection') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                allspans[ci].innerHTML = '<img src="media/arrowNull.gif" />';
            }
        }
    }
    
	for(var rowIndex=0; rowIndex < table.rows.length; rowIndex++) {
		var row = table.rows[rowIndex];
		var rowClassAppend = (rowIndex % 2 == 0) ? "_tblRow0" : "_tblRow1";
		var currentClassNameLength = (row.className.length -8);
 		row.className = (row.className.substr(0,currentClassNameLength)+rowClassAppend);
		
	}
   
    span.innerHTML = ARROW;
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}

function ts_sort_date(a,b) {
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa.length == 10) {
        dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
    } else {
        yr = aa.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
    }
    if (bb.length == 10) {
        dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
    } else {
        yr = bb.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
    }
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}

function ts_sort_currency(a,b) { 
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}

function ts_sort_numeric(a,b) { 
    aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function ts_sort_default(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}


function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}


//Industry Form Access
function getSpecificationsPage(basePath, optionId)
{
	var url = basePath + "popupPages/Specifications.aspx?";
	url += "optionId=" + optionId;
	var name = "_blank";
	var features = "location=no,menubar=no,directories=no,toolbar=no,status=yes,resizable=yes,scrollbars=yes";
	//Set the window size (window automatically centered by this function)
	var height = 250;
	var width = 450;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	features += ",top=" + top + "px";
	features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}

//Industry Form Access
function getRequestAQuoteForm(basePath, manufacturer, model, year, image)
{
	//var url = basePath + "popupForms/quoteRequest/QuoteRequest.aspx?";
	var url = basePath + "popupForms/dynamic/Request.aspx?";
	url += "manufacturer=" + manufacturer;
	url += "&model=" + model;
	url += "&year=" + year;
	url += "&image=" + image;
	var name = "_blank";
	var features = "location=no,menubar=no,directories=no,toolbar=no,status=yes,resizable=yes,scrollbars=yes";
	//Set the window size (window automatically centered by this function)
	var height = 480;
	var width = 400;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	features += ",top=" + top + "px";
	features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}

function getRequestAQuoteForm(basePath, manufacturer, model, year, image, productType)
{
	//var url = basePath + "popupForms/quoteRequest/QuoteRequest.aspx?";
	var url = basePath + "popupForms/dynamic/Request.aspx?";
	url += "manufacturer=" + manufacturer;
	url += "&model=" + model;
	url += "&year=" + year;
	url += "&image=" + image;
	url += "&productType=" + productType;
	var name = "_blank";
	var features = "location=no,menubar=no,directories=no,toolbar=no,status=yes,resizable=yes,scrollbars=yes";
	//Set the window size (window automatically centered by this function)
	var height = 480;
	var width = 400;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	features += ",top=" + top + "px";
	features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}

function getRequestAQuoteForm(basePath, manufacturer, model, year, image, productType, industryId, aspect, partNumber, notAvailable)
{
	//alert('getRequestAQuoteForm(' + basePath + ',' + manufacturer + ',' + model + ',' + year + ',' + year + ',' + image + ',' + productType + ',' + industryId + ',' + aspect + ',' + notAvailable + ')');
	var url = basePath + "popupForms/dynamic/Request.aspx?";
	url += "manufacturer=" + manufacturer;
	url += "&model=" + model;
	url += "&year=" + year;
	url += "&image=" + image;
	url += "&productType=" + productType;
	url += "&industryId=" + industryId;
	url += "&aspect=" + aspect;
	url += "&partNumber=" + partNumber;
	if(notAvailable)
	{
		url += "&productNotAvailable=true";
	}
	var name = "_blank";
	var features = "location=no,menubar=no,directories=no,toolbar=no,status=yes,resizable=yes,scrollbars=yes";
	//Set the window size (window automatically centered by this function)
	var height = 480;
	var width = 400;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	features += ",top=" + top + "px";
	features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}

function getRequestAQuoteFormFromTFG(basePath, manufacturer, model, year, image, productType, industryId, aspect, notAvailable, vehicleYear, vehicleMake, vehicleModel, vehicleStyle, tireSize)
{
	//alert('getRequestAQuoteFormFromTFG(' + basePath + ',' + manufacturer + ',' + model + ',' + year + ',' + image + ',' + productType + ',' + industryId + ',' + notAvailable + ',' + vehicleYear + ',' + vehicleMake + ',' + vehicleModel + ',' + vehicleStyle + ',' + tireSize + ')');
	var url = basePath + "popupForms/dynamic/Request.aspx?";
	url += "manufacturer=" + '';
	url += "&model=" + '';
	url += "&year=" + '';
	url += "&image=" + '';
	url += "&productType=" + productType;
	url += "&industryId=" + industryId;
	url += "&aspect=" + aspect;
	url += "&vehicleYear=" + vehicleYear;
	url += "&vehicleMake=" + escape(vehicleMake);
	url += "&vehicleModel=" + escape(vehicleModel);
	url += "&vehicleStyle=" + escape(vehicleStyle);
	url += "&tireSize=" + tireSize;
	if(notAvailable)
	{
		url += "&productNotAvailable=true";
	}
	var name = "_blank";
	var features = "location=no,menubar=no,directories=no,toolbar=no,status=yes,resizable=yes,scrollbars=yes";
	//Set the window size (window automatically centered by this function)
	var height = 480;
	var width = 400;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	features += ",top=" + top + "px";
	features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}

function getRequestABrochureForm(basePath, manufacturer, model, year, image)
{
	//alert('getRequestABrochureForm(' + basePath + ',' + manufacturer + ',' + model + ',' + year + ',' + year + ',' + image + ')');
	var url = basePath + "popupForms/brochureRequest/BrochureRequest.aspx?";
	url += "manufacturer=" + manufacturer;
	url += "&model=" + model;
	url += "&year=" + year;
	url += "&image=" + image;
	
	var name = "_blank";
	var features = "location=no,menubar=no,directories=no,toolbar=no,status=yes,resizable=yes,scrollbars=yes";
	
	//Set the window size (window automatically centered by this function)
	var height = 480;
	var width = 400;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	features += ",top=" + top + "px";
	features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}

function getFinancingApplication(basePath, manufacturer, model, year, amount, image)
{
	var url = basePath + "financing/Financing.aspx?";
	url += "manufacturer=" + manufacturer;
	url += "&model=" + model;
	url += "&year=" + year;
	url += "&amount=" + amount;
	url += "&image=" + image;
	
	var name = "_blank";
	var features = "location=no,menubar=no,directories=no,toolbar=no,status=no,resizable=yes,scrollbars=yes";

	//Set the window size (window automatically centered by this function)
	var height = 480;
	var width = 640;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	//features += ",top=" + top + "px";
	//features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}

function getShowcasePrintProductComparison(basePath, products, areOptions)
{
	var url = basePath + "showcaseprintprodcompare.htm?";
	url += "products=" + products;
	if(areOptions){
		url += "&areOptions=true";
	}
	var name = "_blank";
	var features = "location=no,menubar=yes,directories=no,toolbar=no,status=yes,resizable=yes,scrollbars=yes";

	//Set the window size (window automatically centered by this function)
	var height = 480;
	var width = 760;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	features += ",top=" + top + "px";
	features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}

function getCorporatePromotionsPrintPage(url){	
	var name = "_blank";
	var features = "location=no,menubar=yes,directories=no,toolbar=no,status=yes,resizable=yes,scrollbars=yes";

	//Set the window size (window automatically centered by this function)
	var height = 480;
	var width = 760;
	
	var screenHeight = window.screen.height;	
	var screenWidth = window.screen.width;
	var top = parseInt((screenHeight - height) / 2);
	var left = parseInt((screenWidth - width) / 2);
	features += ",top=" + top + "px";
	features += ",left=" + left + "px";
	features += ",width=" + width + "px";
	features +=",height=" + height + "px";
	
	window.open(url, name, features);
}
//----------------------------- Flash Object Triggering ----------------------------//
var flashObjectCollection = new Object();
function WriteFlashObjects()
{
    if(flashObjectCollection)
    {
        for(var tag in flashObjectCollection)
        {
            flashObjectCollection[tag].write(tag);
        }
    }
}
BindEvent(window, "onload", WriteFlashObjects);
//----------------------------------------------------------------------------------//

///////////////////////////////////// IMAGE LIBRARY //////////////////////////
// JScript source code
function ImageLib() {
    _imageLib = this;
    this.buttons = new Buttons();
    this.preLoader = new PreLoader();
}

function PreLoader() {
    this.count = 0;
}

PreLoader.prototype.add = function(image, path) { 
    //the image parameter must be an image
    if (!image.src) return;
    //create new image
    var oImage = new Image;
    //bind events
    oImage.onload = PreLoader.prototype.onload;
    //extend image object
    oImage.preLoader = this[this.count];
    oImage.reference = image;
    //add image to the buttons collection
    this[this.count] = oImage;
    //increment count
    this.count++;
    //removed onload event from reference image
    image.onload = null 
    //load image
    oImage.src = path;
}

PreLoader.prototype.onload = function() {
    this.reference.src = this.src;
}

function Buttons() {
    this.count = 0;
}

Buttons.prototype.add = function(image){
    var sId;
    var sState;
    //the parameter must be an image
    if (!image.src) return;
    //The image must have a valid ID
    try {
        sId = image.id;
    } 
    catch(e) {
        return e;
    }
    //was a state parameter passed in?
    if (arguments.length > 1) {
        sState = arguments[1].toString();
        switch (sState) {
            case "0" :
                sState = "inactive";
                break;
            case "1" :
                sState = "active";
                break;
            default:
                sState = "inactive";
                break;
        }
    } else {
        sState = "inactive"
    }
    //Add button to the buttons collection
    Buttons.prototype[sId] = new Button(image, sState);
    //increment button count
    this.count++;
    
    //bind events to image if inactive
    if (sState == "inactive") {
        image.button = this[sId];
        image.onmouseover = Button.prototype.over;
        image.onmouseout = Button.prototype.out;
    }
    
    image.onload = null;
    
    //return reference to button
    return this[sId];
}

function Button(image, state) {
    var sPath, sExtension, sHoverPath;
    this.id = image.id;
    this.boundImage = image;  //reference to image
    this.isLoaded = false; //is the hover image loaded
    this.inert = new Image; //the inert state
    this.hover = new Image; //the hover state
    
    //load inert state
    this.inert.src = image.src;  
  
    sExtension = image.src.substr(image.src.length - 3, image.src.length);
    //get path
    if (state == "inactive") {
        sPath = image.src.substr(0, image.src.length - 4);
    } else {
        sPath = image.src.substr(0, image.src.length - 6);
    }  
    sHoverPath = sPath + "_h." + sExtension;
    
    //load hover by naming convention
    this.hover.onload = Button.prototype.loaded;
    this.hover.button = this;
    this.hover.src = sHoverPath;
}

Button.prototype.over = function(){
    var oElement;
    if (this.button) {
        oElement = this.button;
    } else {
        oElement = this;
    }
    if (oElement.isLoaded == false) return;
    if (oElement.boundImage.src == oElement.hover.src) return;
    oElement.boundImage.src = oElement.hover.src;
    return;
}

Button.prototype.out = function(){
    var oElement;
    if (this.button) {
        oElement = this.button;
    } else {
        oElement = this;
    }
    if (oElement.isLoaded == false) return;
    if (oElement.boundImage.src == oElement.inert.src) return;
    oElement.boundImage.src = oElement.inert.src;
    return;
}

Button.prototype.loaded = function() {
    this.button.isLoaded = true;
    return;
}

Button.prototype.setHover = function(path) {
    try {
        this.hover.src = path;
    } 
    catch (e) {
        return e;
    }
    return;
}

Button.prototype.toString = function(){
    return this.id;
}

var imageLib = new ImageLib();
///////////////////////////////////// END : IMAGE LIBRARY : END //////////////////////////
//////////////////

function doSubmitGoogle(address, city, state, zipcode){
		var query = address + "," + city + "," + state + "," + zipcode;
		document.GoogleLocalMap.q.value = query;
		window.open('','processor_window','menubar=no,toolbar=yes,resizable=yes,status=no,scrollbars=auto,left=25,top=25');
		document.GoogleLocalMap.target = "processor_window";

		document.GoogleLocalMap.submit();
	}

function getCouponPrint(couponId){
    var couponObj = document.getElementById(couponId);
    var cssFiles = document.getElementsByTagName('link');
    var width=400;
    var height=200;
    var viewer=window.open('','viewer','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width='+width+',height='+height+',left=200,top=50');
    viewer.document.open();
    viewer.document.write('<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n');
    viewer.document.write('<html id=\"couponPopUp\">\n');
    viewer.document.write('<head>\n');
    viewer.document.write('<title>Coupon</title>\n');
    for(var x = 0; x < cssFiles.length; x++){
    viewer.document.write('<link rel=\"stylesheet\" type=\"text/css\" href=\"'+cssFiles[x].href+'\"/>\n');
    }
    viewer.document.write('</head>\n');
    viewer.document.write('<body leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\" class=\"couponDisplayPopup\">\n');
    viewer.document.write('<div class=\"couponPrint\">\n');
    viewer.document.write(couponObj.innerHTML+'\n');
    viewer.document.write('</div>\n');
    viewer.document.write('<div class=\"couponControls\"><input class=\"ecomm_button\" type=\"button\" name=\"print\" value=\"Print\" onClick=\"window.print()\"><input class=\"ecomm_button\" type=\"button\" name=\"close\" value=\"Close\" onClick=\"window.close()\"></div>\n');
    viewer.document.write('</body>\n');
    viewer.document.write('</html>\n');
    viewer.document.close();
}

function getGalleryDisplayImg(IMAGE){
    var pic = new Image();
    pic.onload = initGalleryPopUp;
    pic.src = IMAGE;
}

function initGalleryPopUp(){
    var pic = this;
    var cssFiles = document.getElementsByTagName('link');
    var width=(pic.width+40);
    var height=(pic.height+60);
    var viewer=window.open('','viewer','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width='+width+',height='+height+',left=200,top=50');
    viewer.document.open();
    viewer.document.write('<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n');
    viewer.document.write('<html>\n');
    viewer.document.write('<head>\n');
    viewer.document.write('<title>Gallery</title>\n');
    for(var x = 0; x < cssFiles.length; x++){
        viewer.document.write('<link rel=\"stylesheet\" type=\"text/css\" href=\"'+cssFiles[x].href+'\"/>\n');
    }
    viewer.document.write('</head>\n');
    viewer.document.write('<body leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\" class=\"galleryDisplayPopup\">\n');
    viewer.document.write('<table class=\"galleryDisplay_tbl\" align=\"center\" width=\"'+pic.width+'\" border=\"0\" cellspacing=\"10\" cellpadding=\"0\">\n');
    viewer.document.write('<tr class=\"galleryDisplay_tblRow\" >\n');
    viewer.document.write('<td class=\"galleryDisplay_tblCell\"  align=\"center\" valign=\"top\"><image src=\"'+pic.src+'\"</td>\n');
    viewer.document.write('</tr>\n');
    viewer.document.write('<tr class=\"galleryDisplay_tblRow\" >\n');
    viewer.document.write('<td class=\"galleryDisplayControls_tblCell\" align=\"right\" valign=\"middle\"><input class=\"ecomm_button\" type=\"button\" name=\"close\" value=\"Close\" onClick=\"window.close()\"></td>\n');
    viewer.document.write('</tr>\n');
    viewer.document.write('</table>\n');
    viewer.document.write('</body>\n');
    viewer.document.write('</html>\n');
    viewer.document.close();
}

primaryNavInit = function() {
    if (document.all&&document.getElementById) {
        navRoot = document.getElementById('primeNavList');
        if(navRoot != undefined)
        {
            for (i=0; i<navRoot.childNodes.length; i++) {
                node = navRoot.childNodes[i];
                if (node.nodeName=='LI') {
			var childNodeIndex = null;
			//Start Child Node Search
			for(var childIndex=0; childIndex < node.childNodes.length; childIndex++) {
				var testNode = node.childNodes[childIndex];
				if (testNode && testNode.nodeName == 'UL') {
					childNodeIndex = childIndex;
					break;
				}
			}
			//End Child Node Search

			  //Start Child Node Processing
			  if (childNodeIndex != null) {
				var myIndex = new Number(childNodeIndex);
                     node.onmouseover=function() {
				this.childNodes[myIndex].style.display='block';
			   }
                     node.onmouseout=function() {
                         this.childNodes[myIndex].style.display='none';
                     }
			  }
			  //End Child Node Processing
		   }
            }
        }
    }
}
function clearForm(formIdent) 
{ 
  var form, elements, i, elm; 
  form = document.getElementById 
    ? document.getElementById(formIdent) 
    : document.forms[formIdent]; 

	if (document.getElementsByTagName)
	{
		elements = form.getElementsByTagName('input');
		for( i=0, elm; elm=elements.item(i++); )
		{
			if (elm.getAttribute('type') == "text")
			{
				elm.value = '';
			}
		}
	}

	// Actually looking through more elements here
	// but the result is the same.
	else
	{
		elements = form.elements;
		for( i=0, elm; elm=elements[i++]; )
		{
			if (elm.type == "text")
			{
				elm.value ='';
			}
		}
	}
}

function toggleTradeDiv(value) {
	var elm = document.getElementById("requestQuoteTrade");
	if(elm!=null) elm.style.display = (value || value==null) ? "" : "none";
}

function getToggleForTrade() {
	var el = getElementsByClass("requestQuoteCheckWithTrade");
	if(el!=null) el = el[0];
	if(el!=null) el = el.childNodes[0];
	if(el!=null) toggleTradeDiv(el.checked);
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function AlertMe(ctrl)
{
    ctrl.selectedIndex = 0;
    alert(ctrl);
}
BindEvent(window,"onload", primaryNavInit); 

