/*
* $Date: 2007.04.21
* $Author: Matthew Burroughs <matthew@kaango.com>
*
* ====================================================================
*
* Copyright (c) 2006 Kaango, Inc..  All rights reserved.
* Note: Original work copyright to respective authors
*
*
*/
var forceValidCatSelection = false;
var isValidCatSelection = false;

var lev = null;
var req = null;

/*************** AJAX User Feedback Events  ******************/
function showPleaseWait() {
// We will display a "please wait" message to the user to convey that page content is changing.
    var kaango_pleaseWait = document.getElementById("kaango_pleaseWait");
    var kaango_pleaseWait_height = 195+(20*lev);
    var kaango_pleaseWait_padding = 65+(20*lev/8);
    
    if ( document.getElementById("userIsLoggedIn").value == '0') {
        kaango_pleaseWait.innerHTML =                               "<div style='z-index: 11; position: absolute; text-align:center; filter:alpha(opacity=50);-moz-opacity:.50;opacity:.50; background-color: #eeeeee; width: 779px; height: "+kaango_pleaseWait_height+"px; padding-top:"+kaango_pleaseWait_padding+"px;'></div>";
        kaango_pleaseWait.innerHTML = kaango_pleaseWait.innerHTML + "<div style='z-index: 12; position: absolute; text-align:center; font-size:20px; font-weight:bold; color: #000000; background:transparent; width: 779px; height: "+kaango_pleaseWait_height+"px; padding-top:"+kaango_pleaseWait_padding+"px;'>- Please Wait -</div>";
    } else {
        kaango_pleaseWait.innerHTML =                               "<div style='z-index: 11; position: absolute; text-align:center; filter:alpha(opacity=50);-moz-opacity:.50;opacity:.50; background-color: #eeeeee; width: 779px; height: "+kaango_pleaseWait_height+"px; padding-top:"+kaango_pleaseWait_padding+"px;'></div>";
        kaango_pleaseWait.innerHTML = kaango_pleaseWait.innerHTML + "<div style='z-index: 12; position: absolute; text-align:center; font-size:20px; font-weight:bold; color: #000000; background:transparent; width: 779px; height: "+kaango_pleaseWait_height+"px; padding-top:"+kaango_pleaseWait_padding+"px;'>- Please Wait -</div>";
    }
}

function hidePleaseWait() {
// To complete the AJAX request, we will erase the "please wait" notification the user was given.
    tryEnableSubmit();
  
    var kaango_pleaseWait = document.getElementById("kaango_pleaseWait");
    kaango_pleaseWait.innerHTML = "";
}

function tryEnableSubmit() {
    document.getElementById("onlineAd_row04").style.display = "";
    document.getElementById("onlineAd_row05").style.display = "";
    var topAndBottom = document.getElementById("isEdit").value;
    
    var kaango_pleaseWaitSubmit = document.getElementById("createAd_submit");
    if ( topAndBottom == true ) var kaango_pleaseWaitSubmit_top = document.getElementById("createAd_submit_top");
    
    if ( document.getElementById("userIsLoggedIn").value == '0') {
        kaango_pleaseWaitSubmit.disabled = true;
	    if ( topAndBottom == true ) kaango_pleaseWaitSubmit_top.disabled = true;
    } else {
        if ( isValidCatSelection == true || forceValidCatSelection == true ) {
            var kaango_status = document.getElementById("statusHidden");
	       if ( kaango_status.value != '' && kaango_status.value >= 0 ) {
                kaango_pleaseWaitSubmit.disabled = false;
                if ( topAndBottom == true ) kaango_pleaseWaitSubmit_top.disabled = false;
                
	       } else {
	           kaango_pleaseWaitSubmit.disabled = true;
	           if ( topAndBottom == true ) kaango_pleaseWaitSubmit_top.disabled = true;
	       }
    	    
        } else {
            kaango_pleaseWaitSubmit.disabled = true;
            if ( topAndBottom == true ) kaango_pleaseWaitSubmit_top.disabled = true;
        }
    }
}

function forceEnableSubmit() {
    var topAndBottom = document.getElementById("isEdit").value;
    document.getElementById("createAd_submit").disabled = false;
    
	if ( topAndBottom == true ) document.getElementById("createAd_submit_top").disabled = false;
	document.getElementById("kaango_pleaseWait").innerHTML = "";

	if ( document.getElementById("userIsLoggedIn").value == '0') {
    	document.getElementById("onlineAd_row04").style.display = "none";
    	document.getElementById("onlineAd_row05").style.display = "none";
    }
}

/*************** AJAX For Category Selection  ****************/
/**
 * The function which will AJAX in a select box of sub-categories to a selected category.
 * 
 */
function makeCategoryRequest(url, level) {
    if(window.XMLHttpRequest)
        req = new XMLHttpRequest();
    else if(window.ActiveXObject)
        req = new ActiveXObject("Microsoft.XMLHTTP");

    showPleaseWait();

    req.onreadystatechange = processCategoryChange;
    req.open("GET",url,true);
    req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    req.send(null);

    lev = level;
}

/**
 * Action to take upon the arrival of the AJAX from makeCategoryRequest()
 * 
 */
function processCategoryChange() {
    if ( req.readyState == 4 ) {
        if ( req.status == 200 ) {
// Until we can determine that this is a valid category selection, assume otherwise.
            isValidCatSelection = false;
            
            var id = "catOptions"+lev;
            var html = document.getElementById(id);
            html.innerHTML = req.responseText;
            
            // get the category id
            id = "c"+(lev-1);
            var selectCats = document.getElementById(id);
            var catID = selectCats.value;
            id = "c"+lev;
            var nextLevelCats = document.getElementById(id);
            /*
             *  Display the adult message when appropriate.
             */
            var numericCatID = -1;
            if ( catID.indexOf("|") ) {
                    var pieces = catID.split("|");
                    numericCatID = pieces[0];
            }
            //alert(id);
            //alert(numericCatID);
            if(id == 'c1' && numericCatID == 1253)
            {
                document.getElementById('adult_message').style.display = "block";
            }
            else if(id == 'c1')
            {
                document.getElementById('adult_message').style.display = "none";
            }
            
// Check to ensure the user selected a valid category (identify case where the user picked a null option)
            if ( catID == "-1" ) {
                html.innerHTML = "";
                
                var kaango_adNaturePanel = document.getElementById("adNaturePanel");
                kaango_adNaturePanel.innerHTML = ""
                clearPricingBox();
                hidePleaseWait();
// Detect the case where a category was selected that has no subcategories.
            } else if ( nextLevelCats.length == 0 ) {
                isValidCatSelection = true;
                html.innerHTML = "";
               
                // get the category id
                catID = selectCats.value;

                var sellerStatusField = document.getElementById("status");
                var allowLiquidatorField = document.getElementById("allowLiquidator");
                if ( catID.indexOf("|") ) {
                    var pieces = catID.split("|");
                    catID = pieces[0];
                    var sellerStatus = pieces[1];
                    var allowLiquidator = pieces[2];
                    var altURLStatus = pieces[3];
                    
                    unclearPricingBox();
                    updatePricingBox();
                    
                    if ( altURLStatus == 'INT' ) {
                        document.getElementById("createAd_submit").value = "Continue to Partner Site >>";
                    } else {
                        document.getElementById("createAd_submit").value = "Save & Continue >>";
                    }
                    
                    if ( sellerStatus.toLowerCase() == 'all' ) {
                        unlockProSeller();
                    } else if ( sellerStatus.toLowerCase() == 'professional' ) {
                        lockProSellerOn();
                    }  else if ( sellerStatus.toLowerCase() == 'private' ) {
                        lockProSellerOff();
                    }
                    
                    allowLiquidatorField.value = allowLiquidator;                    
                    updateLiquidator();
                    
                    makePanelRequest( catID );                    
                }
            } else {
                // get the category id
                catID = selectCats.value;
                if ( catID.indexOf("|") ) {    
                    var pieces = catID.split("|");
                    catID = pieces[0];
                    var altURLStatus = pieces[3];

                    clearPricingBox();
                    if ( altURLStatus == 'INT' ) {
                        // Hide the seller status box, since that data is no longer relevant.
                        document.getElementById("onlineAd_row04").style.display = "none";
                        
                        // Hide the adNature panel, since that data is no longer relevant.
                        var html = document.getElementById("adNaturePanel");
                        html.innerHTML = "";
                        
                        document.getElementById("createAd_submit").value = "Continue to Partner Site >>";
                    } else {
                        document.getElementById("createAd_submit").value = "Save & Continue >>";
                    }
                }

                hidePleaseWait();
            }

            var start = (parseInt(lev)+1);
            for ( var i = start; i <= 7; i++ ) {
                id = "catOptions"+i;
                html = document.getElementById(id);
                html.innerHTML = "";
            }
            
            if ( altURLStatus == 'INT' ) {
    			forceEnableSubmit();
			}
                    
            // Absolutely ensure that the "Please Wait" overlay is gone.
            //var kaango_pleaseWait = document.getElementById("kaango_pleaseWait");
    		//kaango_pleaseWait.innerHTML = "";

        }
    }
}

function updatePricingBox() {
    var id = "c"+(lev-1);
    var selectCats = document.getElementById(id);
    
    // Get the category id with its details.
    var catID = selectCats.value;
    if ( catID.indexOf("|") ) {
        var pieces = catID.split("|");
    } else {
        return false;
    }
    
    var catID = pieces[0];
    var sellerStatus = pieces[1];
    var allowLiquidator = pieces[2];
    var altURLStatus = pieces[3];
    var catPrice = parseFloat(pieces[4]) / 100;
    var catPricePro = parseFloat(pieces[5]) / 100;
    var freePix = pieces[6];
    var freePixPro = pieces[7];
    var freeDays = parseInt(pieces[8]);
    var freeDaysPro = parseInt(pieces[9]);
    var hasBundles = parseInt(pieces[10]);
    var hasBundlesPro = parseInt(pieces[11]);
                    
    var sellerStatus = document.getElementById("status").value;
    if ( sellerStatus != '1' ) {
        document.getElementById("costDetail_feeInsertionText_text").innerHTML = catPrice.toFixed(2);
        document.getElementById("costDetail_calculatedCost_text01").innerHTML = catPrice.toFixed(2);
        document.getElementById("costDetail_calculatedCost_text02").innerHTML = catPrice.toFixed(2);
        document.getElementById("costDetail_freePix_text").innerHTML = freePix;
    
        expirationDate = new Date();
        expirationDate = new Date((expirationDate.getMonth()+1) + "/" + (expirationDate.getDate()+freeDays) + "/" + expirationDate.getFullYear());
        document.getElementById("costDetail_adExpiresOnline_text01").innerHTML = formatDate(expirationDate, "MM/dd/yyyy");
        document.getElementById("costDetail_adExpiresOnline_text02").innerHTML = formatDate(expirationDate, "MM/dd/yyyy");
        if ( hasBundles == 1 ) {
        	document.getElementById("divBundleTeaser").style.display = "";
        } else {
        	document.getElementById("divBundleTeaser").style.display = "none";
        }
    } else {
        document.getElementById("costDetail_feeInsertionText_text").innerHTML = catPricePro.toFixed(2);
        document.getElementById("costDetail_calculatedCost_text01").innerHTML = catPricePro.toFixed(2);
        document.getElementById("costDetail_calculatedCost_text02").innerHTML = catPricePro.toFixed(2);
        document.getElementById("costDetail_freePix_text").innerHTML = freePixPro;
    
        expirationDate = new Date();
        expirationDate = new Date((expirationDate.getMonth()+1) + "/" + (expirationDate.getDate()+freeDaysPro) + "/" + expirationDate.getFullYear());
        document.getElementById("costDetail_adExpiresOnline_text01").innerHTML = formatDate(expirationDate, "MM/dd/yyyy");
        document.getElementById("costDetail_adExpiresOnline_text02").innerHTML = formatDate(expirationDate, "MM/dd/yyyy");
        if ( hasBundlesPro == 1 ) {
        	document.getElementById("divBundleTeaser").style.display = "";
        } else {
        	document.getElementById("divBundleTeaser").style.display = "none";
        }
    }
    
	if ( altURLStatus == 'INT' ) {
		forceEnableSubmit();
	} 
}

var mappedFieldReq = null;
/**
 * 
 */
function processMappedField(fieldName,fieldA,fieldB) {

	var p = document.getElementById(fieldName);
	var valA = p.options[p.selectedIndex].value;
    var url = siteURL+"ajaxAdNatureDrawMappedField/"+fieldA+"/"+fieldB+"/"+valA;

	//set fieldB for later use in div container selection
	
	document.getElementById('currentMappedField').value = fieldB;
	var current = document.getElementById('currentMappedField').value;

    if(window.XMLHttpRequest)
        mappedFieldReq = new XMLHttpRequest();
    else if(window.ActiveXObject)
        mappedFieldReq = new ActiveXObject("Microsoft.XMLHTTP");


    mappedFieldReq.onreadystatechange = processFields;
    mappedFieldReq.open("GET",url,true);
    mappedFieldReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    mappedFieldReq.send(null);

}

/**
 * 
 */
function processFields() {

    if ( mappedFieldReq.readyState == 4 ) {

        if ( mappedFieldReq.status == 200 ) {

			//fetch current fieldID (fieldB)
			var current = document.getElementById('currentMappedField').value;

			//assign return ajax content to container
			document.getElementById('mapField_'+current).innerHTML = mappedFieldReq.responseText;
			document.getElementById('mapField_'+current).style.display = 'inline';
        }
    }
}

function hideMappedFields(fields)
{
	var fieldList = fields.split(",");
	var size = fieldList.length;
	var i = 0;
	for(i=0; i<size; i++)
	{
		document.getElementById('mapField_'+fieldList[i]).style.display = 'none';
	}
}

var panelReq = null;
/**
 * The function which will AJAX in the fields to display on the first panel for a given category ID.
 * 
 */
function makePanelRequest( catID ) {
    var url = siteURL+"ajaxAdNatureDrawPanel/"+catID+"/1";

    if(window.XMLHttpRequest)
        panelReq = new XMLHttpRequest();
    else if(window.ActiveXObject)
        panelReq = new ActiveXObject("Microsoft.XMLHTTP");

    panelReq.onreadystatechange = processPanelChange;
    panelReq.open("GET",url,true);
    panelReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    panelReq.send(null);
}

/**
 * Action to take upon the arrival of the AJAX from makeCategoryRequest()
 * 
 */
function processPanelChange() {
    if ( panelReq.readyState == 4 ) {
        if ( panelReq.status == 200 ) {
            if ( document.getElementById("userIsLoggedIn").value == '1') {
                var html = document.getElementById("adNaturePanel");
                html.innerHTML = panelReq.responseText;
            } else {
				// error message for guest user alerting - they must register to place ad
				// or to a registered user - they must log in to place ad
				var fontSize = '14px';
                var html = document.getElementById("adNaturePanel");
				var content = '<div style="width: 95%; padding: 4px 0 0 0; text-align: center; font-size: '+fontSize+'; font-weight: bold; color: #900; background-color: #ff9; border: 1px solid #900;">';
				content += '<img src="/resources/img/ico/alertIcon.gif" align="absmiddle">To post an ad, you must first <a style="font-size: '+fontSize+'; font-weight: bold;" href="/feSignUp">register</a>.  If you already have an account, please <a style="font-size: '+fontSize+'; font-weight: bold;" href="/feLogin">login</a>.';
				content += '</div><br />&nbsp;';
				html.innerHTML = content;
            }

            hidePleaseWait();
        }
    }
}


/************* AJAX For Additional Category **************/
var addReq = null;
var addLev = null;

function makeAddRequest(url, level)
{
    if(window.XMLHttpRequest)
        addReq = new XMLHttpRequest();
    else if(window.ActiveXObject)
        addReq = new ActiveXObject("Microsoft.XMLHTTP");

    addReq.onreadystatechange = processAdd;
    addReq.open("GET",url,true);
    addReq.send(null);

    addLev = level;
}

function processAdd()
{
    if(addReq.readyState == 4)
    {
        if(addReq.status == 200)
        {
            id = "addOptions"+addLev;
            html = document.getElementById(id);
            html.innerHTML = addReq.responseText;

            id = "a"+addLev;
            selectCats = document.getElementById(id);

            if(selectCats.length == 0)
            {
                html.innerHTML = "";
            }

            start = (parseInt(addLev)+1);
            for(i = start; i <= 7; i++)
            {
                id = "addOptions"+i;
                html = document.getElementById(id);
                html.innerHTML = "";
            }
        }
    }
}

/****************** PHOTOS ********************/

var photoReq = null;

function makePhotoRequest(url) {
    if(window.XMLHttpRequest)
        photoReq = new XMLHttpRequest();
    else if(window.ActiveXObject)
        photoReq = new ActiveXObject("Microsoft.XMLHTTP");

    photoReq.onreadystatechange = processPhoto;
    photoReq.open("GET",url,true);
    photoReq.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    photoReq.send(null);

}

function processPhoto() {
    if ( photoReq.readyState == 4 ) {
        if ( photoReq.status == 200 ) {
            html = document.getElementById("uploadedPhotos");
            html.innerHTML = photoReq.responseText;
			var primaryImage = document.getElementById('primaryImage');
			var primaryImagePath = document.getElementById('primaryImagePath');
			var kaango_ImageSelect = document.getElementById('printAd_imageID');
			var kaango_fontId = document.getElementById('printAd_fontID');
			var kaango_hasFontId = 0;
			if( kaango_fontId )
				kaango_hasFontId = parseInt( kaango_fontId.options[kaango_fontId.selectedIndex].value );
			if( primaryImage && primaryImage.src != '' )
			{
				// they have at least a primary image
				if( primaryImagePath )
				{
					// and id looks like w2p is enabled and adding image is
					// an option for this package, so...
					// update the primary image path saver field
					primaryImagePath.value = primaryImage.src;
					if( kaango_hasFontId )
						makeWTPHnJRequest();
				}
			}
			else
			{
				// they have deleted all their images
					primaryImagePath.value = '';
					if( kaango_hasFontId )
					{
						kaango_ImageSelect.checked = false;
						kaango_ImageSelect.disabled = true;
						document.getElementById("printAd_row06_image").style.display = 'none';
						makeWTPHnJRequest();
					}
			}
        }
    }
}
