/* XMLHttpRequestStuff */
var req; // The Request
var res; // The Response
var theElm;
function getCategoryFabrics(categoryID){		
		var dropDown = document.getElementById('categoryList');
		var urlString = '/XMLResponses/DisplayCategoryFabrics.aspx?categoryID=' + categoryID.value;
		
		theElm = document.getElementById('displayElm');		
		theElm.innerHTML = '<h2>Loading Fabrics</h2><p>Are you are having trouble accessing fabrics? Please review our <a href="/CustomerService.aspx?page=faq">technical requirements</a>. Your browser may not be supported.</p>';
		if(window.ActiveXObject) { // IE
			req = new ActiveXObject("Microsoft.XMLHTTP");
			req.onreadystatechange = processReqChanged; // Function to handle the response
			req.open("POST", urlString, true);
			req.send();
		}
		else if(window.XMLHttpRequest){ // Mozilla family
			req = new XMLHttpRequest();
			req.onreadystatechange = processReqChanged; // Function to handle the response
			req.open("POST", urlString, true);
			req.setRequestHeader('Content-Length', 0);
			req.send(0); 
		}
	}
	
function processReqChanged(){
	if( req.readyState == 4){ // Only if the req is loaded
		if(req.status == "200"){
			theElm.innerHTML = req.responseText; // Show the response
		}else{
			alert("error: " + req.statusText); // Just to show the error.
		}
	}
}


/* NEEDED DO NOT REMOVE THIS! */
function setHiddenValue(theValue, inputId){
	var hiddenElm;
	hiddenElm = document.getElementById(inputId);	
	hiddenElm.value = 0;
	hiddenElm.value = theValue;
	displayPrice();
}

/* Function sets the background fabric pattern of the preview-pane div */
function setTile(usercode) {
//	alert(usercode);
var theElm = document.getElementById('apDiv1');
//theElm.style.background = "url(fabrics/thumb/" + usercode + ") repeat";
theElm.style.background = "url(" + usercode + ") #000000";
//BACKGROUND: url(/images/fabric-tile/.gif) #000000
}

/* VALIDATION */



// Master validate function. Should be called on the onclicks of both buttons. 
// NOTE: This doesn't check the actual radio buttons because their ID's are generated 
// dynamically, for the labels. I think it would be better to check the hidden form values.
// The hidden for values are the ones that are submitted anyways. When a radio button on this
// page is clicked, it actually just sets the value of a hidden input. See the function
// setHiddenValue(theValue, inputId) on this file.
function validateOptionSelectForm(){	
	var isSafari = navigator.userAgent.indexOf('Safari') != -1;
	var returnValue = false; // assume the worst
	var content = document.getElementById('design-wrapper');
	returnValue = validateInputs();
	if( returnValue == false ){
		if (isSafari == false) {
			content.scrollIntoView();
		}
	}
	
	return returnValue;
}

function newFormValidate()  {
	var retunValue;
	returnValue = validateOptionSelectForm();	
	return returnValue;
}

function setErrorMessage(){}

function checkFabricType(radioList){
	var listLen = 0;
	var i;
	var returnValue = false;
	
	listLen = radioList.length;
	// This is not always on the page!
	for( i = 0; i < listLen; i++ ){	
		if( radioList[i].checked == true ){			
			returnValue = true;			
		}
	}	
	return returnValue;
}

// Will display errorMsg in the errorElmId's innerHTML.
// errorElmId should be a DIV of class type error
function displayInputError(errorMsg, errorElmId){	
	errorElm = document.getElementById(errorElmId);
	errorElm.style.visibility = 'visible';
	errorElm.innerHTML = errorMsg;
}

function removeErrorMessage(errorElmId){
	errorElm = document.getElementById(errorElmId);
	errorElm.style.visibility = 'hidden';
	errorElm.innerHTML = '';
}




function validateInputs(){
	var styleElm = document.getElementById('styleId');
	var sleeveElm = document.getElementById('sleeveId'); 	
	var neckElm = document.getElementById('neckId'); 	
	var lengthElm = document.getElementById('lengthId');
	var fabricElm = document.getElementById('fabricId'); 	
	
	var ftLength = 0; // Length of the fabricTypeElm.
	var ftCheck = false;
	var returnValue = true; // If this is false the form will not submit
	
	//document.styleSelect.focus;
	// Make sure all of the hidden elements have a value 
	// greater than zero, and also that the values are no
	// NAN's. 
	
	// Style check
	//if((styleElm.value <= 0)){
	//	displayInputError('Required', 'styleError');
	//	returnValue = false;
	//}else{
		removeErrorMessage('styleError');
	//}
	
	// Sleeve check
	//if((sleeveElm.value <= 0)){
	//	displayInputError('Required', 'sleeveError');
	//	returnValue = false;
	//}else{
		removeErrorMessage('sleeveError');
	//}
	
	// Neckline check
	//if((neckElm.value <= 0)){
	//	displayInputError('Required', 'neckError');
	//	returnValue = false;
	//}else{
		removeErrorMessage('neckError');
	//}
	
	// Length check
	//if((lengthElm.value <= 0)){
	//	displayInputError('Required', 'lengthError');
	//	returnValue = false;
	//}else{
		removeErrorMessage('lengthError');
	//}
	
	// FabricID check
	if((fabricElm.value <= 0)){
		displayInputError('A dress fabric is required. Please pick a type first then select a fabric.', 'fabricError');
		returnValue = false;
	}else{
		removeErrorMessage('fabricError');
	}
	
	var innerCheck = false; // used on fabricSelect, because it's not always on the page.
		
	return returnValue;  // If all is good the form will submit
}

var priceReq
var priceRes
function sendPriceRequest(styleId, fabricType ) {
        var url = '/xmlResponses/DressPrice.aspx?styleId=' + styleId + '&fabricType=' + fabricType;	
        if(window.ActiveXObject) { // IE
			priceReq = new ActiveXObject("Microsoft.XMLHTTP");
			priceReq.onreadystatechange = handlePriceResponse; // Function to handle the priceResponse
			priceReq.open("POST", url, true);
			priceReq.send();
		} 
		else if(window.XMLHttpRequest){ // Mozilla family
			priceReq = new XMLHttpRequest();
			priceReq.onreadystatechange = handlePriceResponse; // Function to handle the priceResponse
			priceReq.open("POST", url, true);
			priceReq.setRequestHeader('Content-Length', 0);
			priceReq.send(0); 
		}       
}

function handlePriceResponse() {
    var priceElm = document.getElementById('dress-price');
	if( priceReq.readyState == 4){ // Only if the req is loaded	    
		if(priceReq.status == "200"){
			priceElm.innerHTML = priceReq.responseText; // Show the response
		}else{
			priceElm.innerHTML = '<span>There was an error getting the dress cost.</span>';
		}
	}

}

function displayPrice() {
    
    var thePrice = 0;
    var styleInput = document.getElementById('styleId');
    var fabricSelect = document.forms[0].fabricSelect;        
    var fabricType = 0;
    var styleId = 0; 
    if( fabricSelect != null ) { 
        var radioLen = fabricSelect.length;  
        for( var i = 0; i < radioLen; i++ )
        {
            if ( fabricSelect[i].checked == true ) {
                fabricType = fabricSelect[i].value;
                break;
            }
        }       
    } else {
        fabricTypeId = document.getElementById('fabricTypeId');
        fabricType = fabricTypeId.value;
    }    
    styleId = styleInput.value;
    sendPriceRequest(styleId, fabricType);
}
/*
function displayPrice() {
    
    var thePrice = 0;
    var styleInput = document.getElementById('styleId');
    var fabricSelect = document.forms[0].fabricSelect;    
    var radioLen = fabricSelect.length;
    var fabricType = 0;
    var styleId = 0;    
    for( var i = 0; i < radioLen; i++ )
    {
        if ( fabricSelect[i].checked == true ) {
            fabricType = fabricSelect[i].value;
            break;
        }
    }       
    styleId = styleInput.value;
    sendPriceRequest(styleId, fabricType);
}
*/

function getNecklines(styleID)
{
    var postdata = postdataStart
        + '<Necklines xmlns="http://tempuri.org/">\n'
        + '<styleID>' + styleID + '</styleID>\n'
        + '</Necklines>\n'
        + postdataEnd;
        
    var headers = new Array("Content-Length", postdata.length,
                        "SOAPAction", "http://tempuri.org/Necklines",
                        "Host", location.hostname);
                        
    $.ajax({
        type: "POST",
        url: "http://" + location.hostname + "/WebServices.asmx?WSDL",
        data: postdata,
        headers: headers,
        contentType: "text/xml; charset=utf8",
        dataType: "xml",
        success: function(xml) {
            var divNecklines = $("#divNecklines");
            var count = xml.getElementsByTagName("Count")[0].firstChild.nodeValue;
            if (count <= 0)
            {
                if (divNecklines.attr("class").indexOf("block") > 0)
                {
                    divNecklines.toggleClass("block");
                    divNecklines.toggleClass("hidden");
                }
            }     
            else
            {
                if (divNecklines.attr("class").indexOf("hidden") > 0)
                {
                    divNecklines.toggleClass("hidden");
                    divNecklines.toggleClass("block");
                }
                
                var necklines = $("#necklinesList");
                necklines.html("");
                
                var html = "";
                var nodes = xml.getElementsByTagName("Neckline");
                for (var i = 0; i < nodes.length; i++)
                {
                    var id = nodes[i].childNodes[0];
                    var name = nodes[i].childNodes[1];
                    var dressDefault = nodes[i].childNodes[2];
                                        
                    var necklineName = "neckLine" + id.firstChild.nodeValue;
                    var onclick = "setHiddenValue('" + id.firstChild.nodeValue + "', 'neckId'); setNeckImage('" + name.firstChild.nodeValue + "'); init(); removeErrorMessage('neckError');";
                    if (dressDefault.firstChild.nodeValue == "true")
                    {                                        
                        html += '<li><input type="radio" onclick="' + onclick + '" id="' + necklineName + '" checked="true" value="' + id.firstChild.nodeValue + '" name="neckLine"><label for="' + necklineName + '">' + name.firstChild.nodeValue + '</label></input></li>';
                    }
                    else
                    {
                        html += '<li><input type="radio" onclick="' + onclick + '" id="' + necklineName + '" value="' + id.firstChild.nodeValue + '" name="neckLine"><label for="' + necklineName + '">' + name.firstChild.nodeValue + '</label></input></li>';
                    }
                }
                necklines.html(html);
            }
        },
        error: function(xml) {
            
        }
    });
}

function getSleeves(styleID)
{
    var postdata = postdataStart
        + '<Sleeves xmlns="http://tempuri.org/">\n'
        + '<styleID>' + styleID + '</styleID>\n'
        + '</Sleeves>\n'
        + postdataEnd;
        
    var headers = new Array("Content-Length", postdata.length,
                        "SOAPAction", "http://tempuri.org/Sleeves",
                        "Host", location.hostname);
                        
    $.ajax({
        type: "POST",
        url: "http://" + location.hostname + "/WebServices.asmx?WSDL",
        data: postdata,
        headers: headers,
        contentType: "text/xml; charset=utf8",
        dataType: "xml",
        success: function(xml) {
            var divSleeves = $("#divSleeves");
            var count = xml.getElementsByTagName("Count")[0].firstChild.nodeValue;
            if (count <= 0)
            {
                if (divSleeves.attr("class").indexOf("block") > 0)
                {
                    divSleeves.toggleClass("block");
                    divSleeves.toggleClass("hidden");
                }
            }     
            else
            {
                if (divSleeves.attr("class").indexOf("hidden") > 0)
                {
                    divSleeves.toggleClass("hidden");
                    divSleeves.toggleClass("block");
                }
                
                var sleeves = $("#sleevesList");
                sleeves.html("");
                
                var html = "";
                var nodes = xml.getElementsByTagName("Sleeve");
                for (var i = 0; i < nodes.length; i++)
                {
                    var id = nodes[i].childNodes[0];
                    var name = nodes[i].childNodes[1];
                    var dressDefault = nodes[i].childNodes[2];
                               
                    var sleeveName = "sleeve" + id.firstChild.nodeValue;
                    var onclick = "setHiddenValue('" + id.firstChild.nodeValue + "', 'sleeveId'); setSleeveImage('" + name.firstChild.nodeValue + "'); init(); removeErrorMessage('sleeveError');";
                    if (dressDefault.firstChild.nodeValue == "true")
                    {                                        
                        html += '<li><input type="radio" onclick="' + onclick + '" id="' + sleeveName + '" checked="true" value="' + id.firstChild.nodeValue + '" name="sleeve"><label for="' + sleeveName + '">' + name.firstChild.nodeValue + '</label></input></li>';
                    }
                    else
                    {
                        html += '<li><input type="radio" onclick="' + onclick + '" id="' + sleeveName + '" value="' + id.firstChild.nodeValue + '" name="sleeve"><label for="' + sleeveName + '">' + name.firstChild.nodeValue + '</label></input></li>';
                    }
                }
                sleeves.html(html);
            }
        },
        error: function(xml) {
            
        }
    });
}