var JSONSpecs;

var designString;
var discountStatus;

var Styles = new Array();
Styles['Shutter'] = [ 'Antebellum' , 'Atlantic' , 'Colonial' , 'Bermuda' , 'Cottage' , 'OldWorld' ];
Styles['Door'] = [ 'Georgian' , 'EarlyAmerican' , 'Continental' , 'Cabana' , 'French' , 'Mission' ];
Styles['Cabinet'] = [ 'Philadelphia','Sonoma','TuxedoPark','Beadboard','Country' ];
Styles['Window'] = [ 'Sash','Casement','Open' ];
Styles['Entry'] = [ 'Traditional','Craftsman','Parisian' ];

function init() 
{
    if(GetCookie("ITEM_COUNT") == null)
    {
	CreateCookie("ITEM_COUNT", 0);
    }

    //Highlight appropriate nav menu based on designer
    if(d_PRODUCT == "Shutter" || d_PRODUCT == 'Door' || d_PRODUCT == 'Cabinet')
    {
	//jsPacker doesn't like strings that start with '_', so it's split here
	document.getElementById(d_PRODUCT + "_" + "Link").className = "active";
    }

    document.PROJECT.reset();
    setupValues();
    setDiscounts(); 
    setGlyphTitle('');
    updateSpecs();
}



function setupValues() {

    //Change default collection/style based on page name
    if(d_SITE == 'raised-panel-shutters')
    {
	d_DEFAULT_COLLECTION = 'Atlantic'; 
	d_DEFAULT_STYLE = 'Cape';
    }
    
    else if(d_SITE == 'bermuda-shutters' || d_SITE == "bahama-shutters")
    {
	d_DEFAULT_COLLECTION = 'Bermuda'; 
	d_DEFAULT_STYLE = 'Governor';
    }
        
    else if(d_SITE == 'board-and-batten-shutters') 
    {
	d_DEFAULT_COLLECTION = 'OldWorld'; 
	d_DEFAULT_STYLE = 'CoteBasque';
    }


    //Change default material based on keyword or page name (if no keyword)
    var matPhrase = d_SITE;
    
    var lastKeyword = GetCookie('last_keyword');
    if(lastKeyword != 'none' && lastKeyword != '' && lastKeyword != null) matPhrase = lastKeyword;

    if(d_PRODUCT != "Shutter")
    {
	if(matPhrase.match(/cedar/i) != null) d_MATERIAL = 'SpanishCedar';
	else if(matPhrase.match(/cherry/i) != null) d_MATERIAL = 'Cherry';
	else if(matPhrase.match(/mahogany/i) != null) d_MATERIAL = 'Mahogany';
	else if(matPhrase.match(/maple/i) != null) d_MATERIAL = 'Maple';
	else if(matPhrase.match(/poplar/i) != null) d_MATERIAL = 'Poplar';
	else if(matPhrase.match(/teak/i) != null) d_MATERIAL = 'Teak';
	else if(matPhrase.match(/walnut/i) != null) d_MATERIAL = 'Walnut';
	else if(matPhrase.match(/oak/i) != null)
	{
	    if(matPhrase.match(/white.*oak|oak.*white/i) != null) d_MATERIAL = 'WhiteOak';
	    else d_MATERIAL = 'RedOak';
	}

	setMatMenu(d_MATERIAL);
    }
    else
    {
	document.getElementById("sec_mats").style.display = 'none';

	//If we are hiding the materials menu, step 4 becomes step 3
	document.getElementById("stepFour").innerHTML = '3';
    }
    

    //If width/height are passed from mini designer, overwrite the defaults
    var newWidth = d_DEFAULT_WIDTH;
    var newHeight = d_DEFAULT_HEIGHT;
    if(window.location.href.indexOf('?') > 0) {
	var thisArgs = window.location.href.substring(window.location.href.indexOf('?') + 1);
	if(thisArgs.indexOf('wid') >= 0 && thisArgs.indexOf('hei') >= 0) {
	    newWidth = thisArgs.match(/wid=\d+/)[0].substring(4);
	    newHeight = thisArgs.match(/hei=\d+/)[0].substring(4);
	}
    }
    
    document.PROJECT.DL.value = newWidth;
    document.PROJECT.DH.value = newHeight;
    document.getElementById("StyleName").innerHTML = d_DEFAULT_COLLECTION + " " + d_DEFAULT_STYLE;
    document.getElementById(d_DEFAULT_COLLECTION).style.display = 'block';
    
    designString = "-ST+" + d_ST + "+-CN+" + d_DEFAULT_COLLECTION + "+-DS+" + d_DEFAULT_STYLE + "+-DL+" + newWidth + "+-DH+" + newHeight + "+-BGW+-DM+" + d_MATERIAL + "+-WW+" + d_WW + "+-WH+" + d_WH;
    
}


function multiAddToCart(mat, pri)
{
    Order('', 1, pri, getDescription(mat), designString.replace(JSONSpecs.PhotoMaterial,mat.replace(/ /g,'')))
}



function changeFlag(flag, value)
{
    updateDesignString(flag, value);
    
    //If we are changing the colleciton, hold off on updating until style is changed as well
    if(flag != "CN")
    {
	updateSpecs();

	if(flag == "DS") document.getElementById("StyleName").innerHTML = JSONSpecs.Collection + " " + JSONSpecs.Style;
    }

    //Collection changes also trigger a style change, and we have to hide/show the correct menus
    else
    {
	for(var i = 0; i < Styles[d_PRODUCT].length; i++)
	{
	    document.getElementById(Styles[d_PRODUCT][i]).style.display = 'none';
	}
	
	var styleMenu = document.getElementById(value);
	styleMenu.style.display = 'block';
	
	changeFlag("DS", styleMenu.options[styleMenu.selectedIndex].id);
    }
}



function updateDesignString(flag, value)
{
    flag = "-" + flag; 
    
    if(designString.indexOf(flag) > -1)
    {
        var Start = designString.substring(0, designString.indexOf(flag));
	var End = designString.substring(designString.indexOf("-", designString.indexOf(flag) + flag.length));
	designString = Start + End;
    }

    designString = flag + "+" + value + "+" + designString;
}





function updateSpecs()
{
    var specRes = RunCGI("/cgi-bin/NewSpecs.cgi?" + designString + "+-JSON");

    if(specRes != "") JSONSpecs = eval("(" + specRes + ")");
    else return;

    //Update the picture asynchronously
    updatePicture();

    //Get default price for current wood type
    var defaultPrice = JSONSpecs.Price;

    //Get dimensions to set later
    var dimens = JSONSpecs.Thickness + '" x ' + JSONSpecs.Width + '" x ' + JSONSpecs.Height + '" ';

    if(discountStatus == 'true')
    {
	var Disc_5  = defaultPrice * .95;
	Disc_5 = Math.round(Disc_5 * 100)/100;
	var Disc_10 = defaultPrice * .90;
	Disc_10 = Math.round(Disc_10 * 100)/100;
	document.getElementById("price1").innerHTML = defaultPrice;
	document.getElementById("price2").innerHTML = Disc_5;
	document.getElementById("price3").innerHTML = Disc_10;
	document.getElementById("price_range").innerHTML = '$' + Disc_10 + ' - $' + defaultPrice + ' (each)';

	//Update dimensions
	document.getElementById('discount_dimens').innerHTML = dimens;
    }

    else
    {
	var miniTable = document.getElementById('mini_price_table');
	
	//Clear price table
	var numRows = 4;
	if(d_PRODUCT == "Shutter") numRows = 2;

	for(var i = 0; i < numRows; i++)
	{
	    if ( miniTable.rows[i].hasChildNodes() )
		while ( miniTable.rows[i].childNodes.length >= 1 )
		    miniTable.rows[i].removeChild( miniTable.rows[i].firstChild );
	}

	
	
	//Build new price table
	var num = JSONSpecs.Prices.length;
	if(num > 8) num = 8;
	if(d_PRODUCT == "Shutter" && num > 4) num = 4;

	for(var i = 0; i < num; i++)
	{
	    var matTH = document.createElement('th');
	    matTH.setAttribute('class','md_mat');
	    matTH.appendChild(document.createTextNode(JSONSpecs.Prices[i].Material));
	    
	    var priTD = document.createElement('td');
	    priTD.setAttribute('class','md_pri');
	    if(showPrices) priTD.appendChild(document.createTextNode("$" + JSONSpecs.Prices[i].Price));

	    var cartAnchor = document.createElement('a');
	    cartAnchor.setAttribute('href','javascript:multiAddToCart("' + JSONSpecs.Prices[i].Material + '" , "' + JSONSpecs.Prices[i].Price + '")');

	    var cartIMG = document.createElement('img');
	    cartIMG.setAttribute('src','/images/buy.png');
	    cartIMG.setAttribute('title','Add to Cart');
	    cartIMG.className = "mini_cart";

	    cartAnchor.appendChild(cartIMG);
	    priTD.appendChild(document.createElement('br'));
	    priTD.appendChild(cartAnchor);
	    
	    if(i < 4)
	    {
		miniTable.rows[0].appendChild(matTH);
		miniTable.rows[1].appendChild(priTD);
	    }

	    else
	    {
		miniTable.rows[2].appendChild(matTH);
		miniTable.rows[3].appendChild(priTD);
	    }
	}

	//Update dimensions
	document.getElementById('mini_dimens').innerHTML = dimens;

    }

    //Update description
    if(JSONSpecs.Description != "" && d_PRODUCT == 'Shutter')
    {
	document.getElementById('StyleInfo').innerHTML = JSONSpecs.Description;
	document.getElementById('StyleInfo').style.display = "block";
    }
    else document.getElementById('StyleInfo').style.display = "none";

    //Update specs area with info
    var relevantSpecs = ["PhotoMaterial" , "SW" , "BH" , "CH" , "DH" , "PT" , "LS" , "LP" , "LSP"];
    var specDisplays = ["Material" , "Stile Width" , "Base Rail" , "Crown Rail" , "Dividing Rail" , "Louver Thickness" , "Louver Size" , "Louver Pitch" , "Louver Spacing"];
    var specAppends = ['' , '"' , '"' , '"' , '"' , '"' , '"' , '\u00B0' , '"'];
    var newSpecTable = document.createElement('table');
    var sp_tbody = document.createElement('tbody');

    for(var i = 0; i < relevantSpecs.length; i++)
    {
	if(JSONSpecs[relevantSpecs[i]])
	{
	    var thisTR = document.createElement('tr');
	    var thisTD1 = document.createElement('td');
	    thisTD1.className = "right";
	    var thisTD2 = document.createElement('td');
	    var thisB = document.createElement('b');
	    var thisTXT1 = document.createTextNode(specDisplays[i] + ':');
	    var thisTXT2 = document.createTextNode(JSONSpecs[relevantSpecs[i]] + specAppends[i]);
	    thisB.appendChild(thisTXT2);
	    thisTD1.appendChild(thisTXT1);
	    thisTD2.appendChild(thisB);
	    thisTR.appendChild(thisTD1);
	    thisTR.appendChild(thisTD2);
	    sp_tbody.appendChild(thisTR);
	}
    }
    
    newSpecTable.appendChild(sp_tbody);
    document.getElementById("specs").removeChild( document.getElementById('spec_table') );
    newSpecTable.setAttribute('id','spec_table');
    document.getElementById("specs").appendChild(newSpecTable);

    //If measurements are outside of the render range, alert the user as to why the picture looks ugly
    //
    //Shutters   Width 10-36  Height 12-120
    //Doors      Width 18-82  Height 36-120
    //Cabinets   Width:12-36  Height 12-72

    if( 
	(JSONSpecs.Product == "SHUTTER" && (JSONSpecs.Width < 10 || JSONSpecs.Width > 36 || JSONSpecs.Height < 12 || JSONSpecs.Height > 120)) ||
	(JSONSpecs.Product == "DOOR" && (JSONSpecs.Width < 18 || JSONSpecs.Width > 82 || JSONSpecs.Height < 36 || JSONSpecs.Height > 120)) ||
	(JSONSpecs.Product == "CABINET DOOR" && (JSONSpecs.Width < 12 || JSONSpecs.Width > 36 || JSONSpecs.Height < 12 || JSONSpecs.Height > 72))
      )
    {
	openUgly();
    }

    else closeUgly();

}



//render image object is global because packer can't handle inline functions
var rimg;

function updatePicture() 
{
    try { document.getElementById('rendering').removeChild(document.getElementById('designerRender')); }
    catch(e) {}

    document.getElementById('loadingIMG').style.display = 'inline';

    rimg = new Image();
    rimg.id = "designerRender";
    rimg.onload = renderLoaded;
    rimg.src = "/PANEL/panel.cgi?-OF+stdout+" + designString + "+-BGW+1";
    rimg.onclick = renderClick;
}

function renderLoaded()
{
    document.getElementById('rendering').appendChild(rimg);
    document.getElementById('loadingIMG').style.display = 'none';
}

function renderClick()
{
    window.location = "/CATALOG/" + JSONSpecs.Style + ".html";
}



function getDescription(matOverride)
{
    var material;
    if(matOverride) material = matOverride;
    else material = JSONSpecs.PhotoMaterial;

    return JSONSpecs.Collection + " " + JSONSpecs.Style + " " + d_PRODUCT + "  " + JSONSpecs.Thickness + "-in.x" + JSONSpecs.Width + "-in.x" + JSONSpecs.Height + "-in. in " + material + " Unfinished";
    
}



function setMatMenu(mat)
{
    var val = 0;
    for(var i = 0; i < document.getElementById('woodType').options.length; i++)
    {
	if(document.getElementById('woodType').options[i].value.match(new RegExp(mat,'i')) != null)
	{
	    val = i;
	    break;
	}
    }
    document.getElementById('woodType').selectedIndex = val;
}



function setDiscounts()
{
    discountStatus = RunCGI("/DiscountStatus.cgi");

    if(discountStatus == 'true') { //Discounts are active
        document.getElementById("discountDiv").style.display = 'block';
        document.getElementById("noDiscountDiv").style.display = 'none';
    }
    
    else { //Discounts are inactive
        document.getElementById("discountDiv").style.display = 'none';
        document.getElementById("noDiscountDiv").style.display = 'block';
    }
}



function setGlyphTitle(txt)
{
    if(txt == '') document.getElementById('glyph_title').innerHTML = '<span class="glyph_title_empty">mouse over styles for more info</span>';
    else document.getElementById('glyph_title').innerHTML = txt;
}

function openMeasure()
{
    document.getElementById("howToMeasure").innerHTML = RunCGI("/measure.html");
    document.getElementById("howToMeasure").style.display = 'block';

    //IE6 needs the select menus hidden
    document.getElementById('sec_style').style.display = 'none';
    document.getElementById('woodType').style.display = 'none';
    document.getElementById('sec_dimens').style.display = 'none';
}

function closeMeasure()
{
    document.getElementById('howToMeasure').style.display = 'none';
    document.getElementById('sec_style').style.display = 'block';
    document.getElementById('woodType').style.display = 'block';
    document.getElementById('sec_dimens').style.display = 'block';
}

function openUgly()
{
    document.getElementById("ugly").style.display = 'block';
}

function closeUgly()
{
    document.getElementById('ugly').style.display = 'none';
}


function getQuote()
{
    var q_email = document.getElementById('q_email').value;
    if(q_email == '' || q_email.indexOf('@') < 0)
    {
	alert("Please enter a valid email address.");
	return false;
    }

    var q_comments = document.getElementById('q_comments').value;
    if(q_comments == '' || q_comments == '*How can we help you?')
    {
	alert("Please enter a question or comment.");
	return false;
    }
    
    var q_name = document.getElementById('q_name').value;
    var q_phone = document.getElementById('q_phone').value;
    var q_design = getDescription();

    var cust_no;
    
    if(GetCookie('cust_no'))
    {
        cust_no = GetCookie('cust_no');
    }
    else
    {
        cust_no = 'none';
    }

    var data = "email=" + q_email + "&name=" + q_name + "&phone=" + q_phone + "&comments=" + q_comments + "&design=" + q_design + "&custno=" + cust_no;

    var xhr = GetHTTP();
    xhr.open('POST', '/quick_quote.cgi', false);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(data);


    if(xhr.responseText.indexOf('mcx--ok') >= 0)
    {
	window.location = "/quote_ack.html";
    }

    else
    {
	alert("There was a problem submitting your quote\nPlease call 412-459-0076 for assistance.");
    }

    //Send tracking data if it exists
    if(GetCookie('tracking'))
    {	
	var cookies = GetCookie('tracking').split('***');
	
	for(var i = 0; i < cookies.length; i++)
	{
            var vals = cookies[i].split('!!!');
            var domain = vals[0];
            var keyword = vals[1];
            var type = vals[2];
            var timestamp = vals[3];
            var ordernum = '0';
	    
            RunCGI('em_tracking.cgi?' + ordernum + '+' + domain + '+' + keyword + '+' + type + '+' + timestamp + '+quick_quote.cgi+' + cust_no);
	}

    }

}

wipedOnce = false;

function wipeComments()
{
    //Only do it on the first click
    if(!wipedOnce)
    {
	document.getElementById('q_comments').value = "";
	wipedOnce = true;
    }
}
