/******************** AJAX Functions ********************/

var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;

function navBar_open()
{
    navBar_canceltimer();
    navBar_close();
    ddmenuitem = $(this).find('ul').css('visibility', 'visible');
}

function navBar_close()
{
    if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
}

function navBar_timer()
{
    closetimer = window.setTimeout(navBar_close, timeout);
}

function navBar_canceltimer()
{
    if(closetimer)
    {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

$(document).ready(function()
{
    $('#navBar > li').bind('mouseover', navBar_open)
    $('#navBar > li').bind('mouseout',  navBar_timer)
});

document.onclick = navBar_close;

/**
 * queryUser()
 * Verifies the coupon code and returns the status of the code.
 * If valid, the total cost is updated.
 * 
 * @param	int			transactionID
 * @param	string		code
 * @return	void
 */
function checkCouponCode(transactionID, code)
{
    var httpRequest = false;
	
    if (window.XMLHttpRequest)
    {
        try
        {
            httpRequest = new XMLHttpRequest();
        }
        catch (e)
        {
            httpRequest = false;
        }
    }
    else if (window.ActiveXObject)
    {
        try
        {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                httpRequest = false;
            }
        }
    }
    else
    {
        httpRequest = false;
    }
	
    if (httpRequest)
    {
        url = "paymentConfirmation.php?ID=" + transactionID + "&opt=checkCoupon&code=" + code + "&ajax=true";
		
        httpRequest.open("get", url, true);
        httpRequest.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");

        httpRequest.onreadystatechange = function ()
        {
            if (httpRequest.readyState == 4)
            {
                var result = Array();
                result     = httpRequest.responseText.split("|");
				
                if ( (httpRequest.responseText == "") || (result[0] == "Invalid") )
                {
                    if (result[1] != undefined)
                    {
                        document.getElementById("totalCost").innerHTML = result[1];
                    }
					
                    document.getElementById("couponID").value      = "";
                    document.getElementById("couponCode").value    = "Invalid Coupon Code";
                }
                else
                {
                    document.getElementById("totalCost").innerHTML = result[1];
                    document.getElementById("couponID").value      = result[0];
                    document.getElementById("couponCode").value    = code;
                }
            }
            else
            {
                document.getElementById("couponCode").value = "Checking...";
            }
        }
		
        httpRequest.send(null);
    }
}

/**
 * queryUser()
 * Presents the users with a popup choice box.  On acceptance of the
 * dialog, an ajax action is carried out.
 * 
 * @param	string		message
 * @param	boolean		ajaxRequest
 * @param	string		query
 * @param	string		targetDiv
 * @param	boolean		showHide
 * @param	string		optQuery
 * @return	void
 */
function queryUser(message, ajaxRequest, query, targetDiv, showHide, optQuery)
{
    answer = confirm(message);
	
    if (answer)
    {
        if (ajaxRequest)
        {
            makeAjaxRequest(targetDiv, query,    showHide);
            makeAjaxRequest(targetDiv, optQuery, showHide);
        }
        else
        {
            window.location.replace(query);
        }
    }
	
    return;
}

/**
 * makeAjaxRequest()
 * Makes an AJAX request.
 * 
 * @param	string		targetDiv
 * @param	string		query
 * @param	boolean		showHide
 * @return	void
 */
function makeAjaxRequest(targetDiv, query, showHide)
{
    var httpRequest    = false;
    var loadingMessage = '<div style="width: 100%; padding: 50px; text-align: center; vertical-align: middle;"><img src="./styles/images/loading.gif" border="0" alt="Loading, please wait" /></div>';
    var doShowHide     = (typeof(showHide) == "boolean") ? showHide : true;
	
    if ( (doShowHide && showHideDiv(targetDiv) ) || (!doShowHide) )
    {
        if (window.XMLHttpRequest)
        {
            try
            {
                httpRequest = new XMLHttpRequest();
            }
            catch (e)
            {
                httpRequest = false;
            }
        }
        else if (window.ActiveXObject)
        {
            try
            {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e)
            {
                try
                {
                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch(e)
                {
                    httpRequest = false;
                }
            }
        }
        else
        {
            httpRequest = false;
        }
		
        if (httpRequest)
        {
            url = query + '&ajax=true';
			
            httpRequest.open("get", url, true);
            httpRequest.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");		// Prevent caching
	
            httpRequest.onreadystatechange = function ()
            {
                if (httpRequest.readyState == 4)
                {
                    document.getElementById(targetDiv).innerHTML = httpRequest.responseText;
                }
                else
                {
                    document.getElementById(targetDiv).innerHTML = loadingMessage;
                }
            }
			
            httpRequest.send(null);
        }
        else
        {
            window.location(query);
        }
    }
	
    return;
}

/**
 * showHideDiv()
 * Displays or hides a division based on it's current visibility.
 * 
 * @param	string		targetDiv
 * @return	void
 */
function showHideDiv(targetDiv)
{
    if ( (document.getElementById(targetDiv).style.display == '') || (document.getElementById(targetDiv).style.display == 'none') )
    {
        showDiv(targetDiv);
		
        if (targetDiv != "referrerOtherField")
        {
            document.getElementById(targetDiv + 'Link').src = './styles/images/collapse.gif';
        }
		
        returnValue = true;
    }
    else
    {
        hideDiv(targetDiv);
		
        if (targetDiv != "referrerOtherField")
        {
            document.getElementById(targetDiv + 'Link').src = './styles/images/expand.gif';
        }
		
        returnValue = false;
    }

    return returnValue;
}

/**
 * showDiv()
 * Shows a division.
 * 
 * @param	string		targetDiv
 * @return	void
 */
function showDiv(targetDiv)
{
    document.getElementById(targetDiv).style.display = 'block';
	
    return;
}

/**
 * hideDiv()
 * Hides a division.
 * 
 * @param	string		targetDiv
 * @return	void
 */
function hideDiv(targetDiv)
{
    document.getElementById(targetDiv).style.display = 'none';
	
    return;
}

/******************** Redirect Functions ********************/

/**
 * redirect()
 * Changes the browsers current location to the provided URL.
 * 
 * @param 	string			url
 * @return	void
 */
function redirect(url)
{
    window.location.replace(url);
	
    return;
}

/******************** General Helper Functions ********************/

/**
 * Adds a new type rating row to the category.
 *
 * @param string category name of the category to add the new type rating row
 *                        to, either "airplane" or "rotorcraft"
 * @return void
 */
function addTypeRating(category)
{
    if (category == 'airplane')
    {
        newRatingNumber = numAirplaneTypeRatings;
        numAirplaneTypeRatings++;
    }
    else if (category == 'rotorcraft')
    {
        newRatingNumber = numRotorcraftTypeRatings;
        numRotorcraftTypeRatings++;
    }

    // Create the new type rating by cloning an existing one
    newId     = category + 'TypeRating_' + newRatingNumber;
    newRating = $('#' + category + 'TypeRating_Cloneable').clone().attr('id', newId);
    
    // Set the name and ID attributes of the new type rating
    newRating.children(':first').attr('name', category + 'TypeRatings[]');
    newRating.children(':first').attr('id',   newId + '_Input');
    
    // Remove the onclick attribute inheritted from the cloned element
    newRating.children(':last').removeAttr('onclick');

    // Set the onclick attribute of the new type rating's remove link
    newRating.children(':last').bind('click', {
        category: category, ratingNumber: newRatingNumber
        }, function(event) {
            removeTypeRating(event.data.category, event.data.ratingNumber);
            return false;
    });

    // Default the new type rating dropdown to the 'Please Select' option
    newRating.children(':first').val('');

    // Fade the new type rating into view
    newRating.fadeIn('fast');

    // Insert the new type rating after the categories last one
    $('#' + category + 'TypeRatings').children(':last').before(newRating);
    
    newRating.show();

    return;
}

/**
 * Removes the selected type rating row from the specified category.
 *
 * @param string category name of the category to remove the type rating row
 *                        from, either "airplane" or "rotorcraft"
 * @param int ratingNumber row number of the type rating to remove
 * @return void
 */
function removeTypeRating(category, ratingNumber)
{
    if ((category == 'airplane') &&
        (numAirplaneTypeRatings - numAirplaneTypeRatingsRemoved > 1))
    {
        numAirplaneTypeRatingsRemoved++;
        
        $('#airplaneTypeRating_' + ratingNumber).fadeOut('fast', function(){
            $(this).remove();
        });
    }
    else if ((category == 'rotorcraft') &&
             (numRotorcraftTypeRatings - numRotorcraftTypeRatingsRemoved > 1))
    {
        numRotorcraftTypeRatingsRemoved++;
        
        $('#rotorcraftTypeRating_' + ratingNumber).fadeOut('fast', function(){
            $(this).remove();
        });
    }
    else
    {
        // Don't remove the last type rating row for the category
        $('#' + category + 'TypeRating_' + ratingNumber).children(':first').val('');
    }
    
    return;
}

/**
 * setCategoryDropDownStatus()
 * Disables the category drop down list if an item from the type
 * drop down list with an index value greater than or equal to 5
 * is selected.
 * 
 * @param	int			selectedIndex
 * @return	void
 */
function setCategoryDropDownStatus(selectedIndex)
{
    if (selectedIndex <= 5)
    {
        document.getElementById("category").disabled = false;
    }
    else
    {
        document.getElementById("category").disabled = true;
    }
	
    return;
}

/**
 * setStateDropDownStatus()
 * Disables the state drop down menu if a country other than "United States"
 * is selected.
 * 
 * @param	string		value
 * @return	void
 */
function setStateDropDownStatus(value)
{
    if ( (value != "USA") && (value != "") )
    {
        document.getElementById("state").disabled = true;
    }
    else
    {
        document.getElementById("state").disabled = false;
    }
	
    return;
}

/**
 * setYearDropDownStatus()
 * Disables the month drop down list if "Present" is chosen from the year
 * drop down list.
 * 
 * @param	string		value
 * @param	string		elementName
 * @return	void
 */
function setYearDropDownStatus(value, elementName)
{
    if (value == "present")
    {
        document.getElementById(elementName).disabled = true;
    }
    else
    {
        document.getElementById(elementName).disabled = false;
    }
	
    return;
}

/**
 * setOtherReferrerFieldStatus()
 * Enables or disables the "other" referrer text field based upon the users
 * selection in the referrer drop down list.
 * 
 * @param	string		value
 * @return	void
 */
function setOtherReferrerFieldStatus(value)
{
    if (value == 10)
    {
        showDiv("referrerOtherField");
    }
    else
    {
        hideDiv("referrerOtherField");
    }
	
    return;
}

/**
 * setApplicationMethodLocationStatus()
 * Disables or enables the application location text field
 * based on the selection of the application method drop
 * down field.
 * 
 * @param	string		value
 * @return	void
 */
function setApplicationMethodLocationStatus(value)
{
    if ( (value == "web_address") || (value == "email_address") || (value == "fax_number") )
    {
        if (value == "web_address")
        {
            if (document.getElementById("applicationLocationValue").value == "")
            {
                document.getElementById("applicationLocationValue").value = "http://";
            }
			
            document.getElementById("applicationLocationLabel").innerHTML = "Web Address:";
        }
        else if (value == "email_address")
        {
            document.getElementById("applicationLocationLabel").innerHTML = "E-mail Address:";
        }
        else // value == "fax_number"
        {
            document.getElementById("applicationLocationLabel").innerHTML = "Fax Number:";
        }
		
        document.getElementById("applicationLocation").style.display = 'block';
    }
    else
    {
        document.getElementById("applicationLocation").style.display = 'none';
    }
	
    return;
}

/**
 * limitText()
 * Limits the text for a textarea to the provided amount.
 * 
 * @param	string		limitField
 * @param	int			limitCount
 * @param	int			limitNum
 * @return	void
 */
function limitText(limitField, limitCount, limitNum)
{
    if (limitField.value.length > limitNum)
    {
        limitField.value = limitField.value.substring(0, limitNum);
    }
    else
    {
        limitCount.value = limitNum - limitField.value.length;
    }
	
    return;
}

/**
 * selectFilter()
 * Redirects the user to the filter selected from the drop down.
 * 
 * @param   selectField A reference to a DOM select instance.
 * @return  void
 */
function selectFilter(selectField)
{
    if (selectField.selectedIndex > 0)
    {
        redirect( escape(selectField.options[selectField.selectedIndex].value).replace(/%20/g, '+') + '-index.html' );
    }
    
    return;
}

/**
 * disableTextSelection()
 * Disables selection (drag and copy) within a specified element.
 * 
 * @param	target
 * @return	void
 */
function disableTextSelection(target)
{
    /***********************************************
	 * Disable Text Selection script- � Dynamic Drive DHTML code library (www.dynamicdrive.com)
	 * This notice MUST stay intact for legal use
	 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
	 ***********************************************/
	
    if (typeof(target.onselectstart) != "undefined")
    {
        // Internet Explorer
		
        target.onselectstart = function()
        {
            return false;
        }
    }
    else if (typeof(target.style.MozUserSelect) != "undefined")
    {
        // Firefox
		
        target.style.MozUserSelect = "none";
    }
    else
    {
        // Others (e.g. Opera)
		
        target.onmousedown = function()
        {
            return false;
        }
    }
	
    target.style.cursor = "default";
	
    return;
}

