//
// requires jQuery 1.2.6
//
/// <reference path="../tools/jquery-1.3.2-vsdoc2.js" />

var lastAEError;
var gftae_delimiter = "|($@?|";
var cEmptyGuid = "00000000-0000-0000-0000-000000000000";



function beforeAppLoad() 
{    
    getDebugFlag();
    loadCommonTranslations();
    getReferringParty();
    getLookupData();
    getApplicationEngineVersion();
}



function ajaxError(method, msg, extra)
{
    $("#jQueryAjaxWorking").dialog("destroy");
    $("#jQueryAjaxAlert").dialog("destroy");

    var status = "";
    var err = "";
    var stack = "";
    
    if (typeof msg == "string")
    {
        err = msg;
    }
    else
    {
        try 
        {
            //extract the message out of the JSON object
            status = msg.statusText;
            err = eval("(" + msg.responseText + ")").Message;
            stack = eval("(" + msg.responseText + ")").StackTrace;
        }
        catch(Error)
        {
            //if we have an error then this isn't a JSON object
            //it's just a string so return it.
            err = msg.responseText;
        }
    }
    
    lastAEError = err;
    
    var email = (hasValue(gftApp._appProps) && hasValue(gftApp._appProps.Email)) ? gftApp._appProps.Email : "cases@gftforex.fogbugz.com";
    
    //only report errors that aren't a result of a Web Services method
    //we report those errors from the server already and with more information
    if (gftApp._logerrors && method.indexOf("Application.asmx") == -1 )
    {
        try 
        {            
            //this is a cross domain submit to fogubugz
            var url = "https://gftforex.fogbugz.com/scoutSubmit.asp";
            var data = "ScoutUserName=Unassigned" +
                      "&ScoutProject=Application Engine" +
                      "&ScoutArea=AutoError" +
                      "&Description=" + method +
                      "&ForceNewBug=0" +
                      "&Extra=" + status + "\n" + err + "\n" + stack + "\n" + extra +
                      "&Email=" + email +
                      "&ScoutDefaultMessage=appStopError()" +
                      "&FriendlyResponse=1" +              
                      "";                      
            $.getJSON(url+"?"+data+"&jsoncallback=?");
         }
         catch(er)
         {            
            appStopError();
         }
    }
                      
}
 
function appStopError()
{
    //var msg = "The application administrator has been notified. We apologize for the inconvenience.";
    var msg = lastAEError + "<br/><br/>";
    msg += translate("APP_ADMIN_NOTIFIED");
    $("#jQueryAjaxError").html(msg);
    $("#jQueryAjaxError").dialog({
            resizable:false,
            closeOnEscape: false
    });
    
    $("#jQueryAjaxError").data("title.dialog", translate("APP_ERROR"));
}
    
function ajaxAlert(title, msg, callback, bShowButtons)
{
    $("#jQueryAjaxAlert").dialog("destroy");
    $("#jQueryAjaxWorking").dialog("destroy");
    
    var stitle = (!hasValue(title)) ? translate("GFT_APP_INFORMATION") : translate(title);
    var sExtra = "<span class=\"ui-icon ui-icon-alert icon_class\"></span>";    
    var btnTextOk = translate("OK");
    
    var buttons = {};
    
    if (bShowButtons)
    {
        buttons[btnTextOk] = function() {
            $("#jQueryAjaxAlert").dialog("close");
            if (typeof callback == "function")
            {
                callback();
            }
        };
    }
   
    $("#jQueryAjaxAlert").html(translate(msg.toString()));
    $("#jQueryAjaxAlert").dialog({
            resizable:false,
            modal:true,
            buttons: buttons,
            closeOnEscape: false,
            width: 450
    });
    
    $("#jQueryAjaxAlert").data("title.dialog", sExtra + stitle);
}

function ajaxWorking(msg)
{
    var stitle = translate("PLEASE_WAIT");    
    var sExtra = "<span class=\"ui-icon ui-icon-disk icon_class\"></span>";    
    var sMsg = (!hasValue(msg)?translate("LOADING_DATA"):translate(msg));
        
    $("#jQueryAjaxWorking").html("<div><div class=\"float_class\"><img src=\"../assets/images/ajax-loader.gif\" />&nbsp;&nbsp;</div><div class=\"working\">" + sMsg + "</div><div>");
    $("#jQueryAjaxWorking").dialog({            
            resizable:false,
            modal:true,
            stack:false,
            autoOpen:false,            
            minHeight: 55,
            maxHeight: 55,
            overlay: {
                opacity: 0.5,
                background: "black"
            },
            position:["center", "0"],
            closeOnEscape: false            
    });   
    $("#jQueryAjaxWorking").data("title.dialog", sExtra+stitle); 

    // Find and remove the close icon
    $("#jQueryAjaxWorking").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar-close").remove();

    //hack to fix a bug when we try to display this from REDIRECTCONFIRM
    $("#jQueryAjaxWorking").css("display", "");       
}


function ajaxAgreement(msg) {
    $("#jQueryAjaxWorking").dialog("destroy");
    $("#jQueryAjaxAlert").dialog("destroy");

    var stitle = translate("PLEASE_WAIT");
    var btnTextClose = translate("LABEL_CLOSE");
    var btnTextPrint = translate("LABEL_PRINT");
    
    var buttons = {};
    buttons[btnTextClose] = function() {
        $(this).dialog("close");
    };

    if (msg.indexOf(".pdf") == -1) {
        buttons[btnTextPrint] = function() {
            $('iframe').each(function(i) {

                // Opera can't print iframes directly, so open a popup with the iframe's content.
            // Note that the new window is deliberately un-styled so that Opera doesn't print white text on a white background.
                if ($.browser.opera || $.browser.msie) {  
                    var printWin = window.open('about:blank', translate("LABEL_PRINT"));
                    var printBody = printWin.document.body;
                    var myBody = this.contentWindow.document.body;
                    $(printBody).html($(myBody).html());

                    printWin.focus();
                    printWin.print();
                } else {
                    this.focus();
                    this.contentWindow.print();
                }
            });
        };
    }

    $("#jQueryAjaxAlert").html(translate(msg.toString()));
    $("#jQueryAjaxAlert").dialog({
        resizable: false,
        modal: true,
        buttons: buttons,
        closeOnEscape: false,
        width: 800,
        height: 600
    });
    $("#jQueryAjaxAlert").data("title.dialog", "");
}


function ajaxConfirm(title, msg, confirmButtonText, confirmCallback, confirmParams, cancelButtonText, cancelCallback, cancelParams, dialogName)
{    
    var dlgName = (!hasValue(dialogName)) ? "jQueryAjaxConfirm" : dialogName;
    var btnTextOk = (!hasValue(confirmButtonText)) ? translate("LABEL_OK") : translate(confirmButtonText);
    var btnTextCancel = (!hasValue(cancelButtonText)) ? translate("LABEL_CANCEL") : translate(cancelButtonText);
    
    var buttons = {};
    buttons[btnTextOk] = function() {                                          
                                        $("#"+dlgName).dialog("close");
                                        $("#"+dlgName).dialog("destroy");
                                        if (typeof confirmCallback == "function")
                                        {                                              
                                            confirmCallback(confirmParams);
                                        }
                                                                            
                                    };
                                    
    buttons[btnTextCancel] = function() {                                         
                                        $("#"+dlgName).dialog("close");
                                        $("#"+dlgName).dialog("destroy"); 
                                        if (typeof cancelCallback == "function")
                                        {                                                
                                            cancelCallback(cancelParams);
                                        }                                            
                                    }; 

        
    var stitle = (title === "") ? translate("CONFIRM_REQUIRED") : translate(title);
    var sExtra = "<span class=\"ui-icon ui-icon-alert icon_class\"></span>";
    $("#"+dlgName).html(translate(msg.toString()));
    $("#"+dlgName).dialog({
            modal: true,
            resizable: false,           
            buttons: buttons,
            width: 450,            
            overlay: {
                opacity: 0.5,
                background: "black"
            },
            closeOnEscape: false
     });
     
     $("#"+dlgName).data("title.dialog", sExtra + stitle);
     
     //hack to fix a bug when we try to display this from REDIRECTCONFIRM
     $("#"+dlgName).css("display", "");
}

function hasValue(object)
{
    var retVal = false;        
    
    if (object === null || object == undefined)
    {
        retVal = false;
    }
    else
    {
        switch(typeof object)
        {            
            case "string":
                retVal = (object !== "");
                break;
            
            case "object":
                retVal = (object.length > 0);
                break;
         
            default:
                retVal = true;
                break;   
        }            
    }
    
    return retVal;
}

function IsChecked(answerItem, answer, answerType, customAnswerValueField)
{
    if ( hasValue(answer) && answer !== 0)
    {   
        //if this is a comma delimited list then find out
        //if our value is in the list (i.e. a checkbox) 
        if ( answerType == "Checkbox" )
        {
            if( $.inArray((answerItem.AnswerValueID).toString(), answer.split(",")) != -1)
            {
                return "checked=\"true\"";
            }
            else 
            {
                return "";
            }
        }
        else
        {   
            var bFound = false;
            
            if (customAnswerValueField == undefined)
            {
                customAnswerValueField = "AnswerValueID";
            }
            if (customAnswerValueField == "country_id")
            {
                bFound = eval("answerItem." + customAnswerValueField) == answer
            }
            else
            {
                bFound = parseInt(eval("answerItem." + customAnswerValueField)) == parseInt(answer)
            }
            
            if (bFound)
            {
                if (answerType == "DropDown")
                    return "selected=\"yes\"";
                else
                    return "checked=\"true\"";
            }
            else 
            {
                return "";
            }            
        }
    }
    else
    {    
        if (answerType == "DropDown")
            return (answerItem.IsDefault == 1 || answerItem.IsDefault == true) ? "selected=\"yes\"" : "";
        else
            return (answerItem.IsDefault == 1 || answerItem.IsDefault == true) ? "checked=\"true\"" : "";        
    }
}

//an easy way to parse a querystring
jQuery.query = function(s) {
    var r = {};
    if (s) {
        var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
        q = q.replace(/\&$/, ''); // remove the trailing &
        
        jQuery.each(q.split('&'), function() {
            var splitted = this.split('=');
            var key = splitted[0];
            var val = splitted[1];
            if (splitted.length > 1)
            {
                // convert numbers
                if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
                // convert booleans
                if (val == 'true') val = true;
                if (val == 'false') val = false;
                // ignore empty values
                if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
            }
        });
    }
    return r;
};

var countryList = null;
var stateList = null;

function getLookupData()
{
    $.ajax({ 
        data: "{}",
        url: "Application.asmx/GetCountries",
        async: false,
        success: function(response) {        
            var data = eval('(' + response.d + ')');
            countryList = data;
        },
        error: function(msg) {            
            ajaxError(this.url, msg, this.data);
        }
    });
    
    $.ajax({         
        data: "{}",
        url: "Application.asmx/GetStates",                
        async: false,         
        success: function(response) {            
            var data = eval('(' + response.d + ')');
            stateList = data;
        },
        error: function(msg) {            
            ajaxError(this.url, msg, this.data);
        }
    });
}


// Begin getReferringParty()
var gftInterface = true;
function getReferringParty()
{
    // Declare variables
    var query = $.query(document.location.href);
    var rpid = 0;
    var applicationType = "";
    var retProp = "";

    // Get the RPID from the query string
    if(hasValue(query.rpid))
        rpid = query.rpid;

    // Get the application type from the query string
    if (hasValue(query.applicationtype))
        applicationType = query.applicationtype;

    // Begin get referring party data        
    $.ajax({
        data: "{applicationTypeName:'" + applicationType +
              "', rpid:" + rpid + "}",
        url: "Application.asmx/GetReferringParty",
        async: false,
        success: function(response) {
            if (hasValue(response.d))
                retProp = eval('(' + response.d + ')');
        },
        error: function(msg) {
            ajaxError(this.url, msg, this.data);

            retProp = "Unknown";
        }
    });
    //--/ End get referring party data

    // Begin hide header and contact
    if (retProp != "")
    {
        gftInterface = retProp[0].gft_interface;

        if (gftInterface == 0 || gftInterface == "No")
        {
            $(".gft-header").remove();
            $(".gft-contact").remove();
        }
    }
    //--/ End hide header and contact    
};
//--/ End getReferringParty()


var blnDebugModeOn = false;
function getDebugFlag()
{
    var blnResult;
    $.ajax({ 
        data: "{'DebugKeyName':'Debug'}",
        url: "Application.asmx/GetDebugFlag",
        async: false,        
        success: function(response) {        
            var data = eval('(' + response.d + ')');
            blnDebugModeOn = data;
        },
        error: function(msg) {            
            ajaxError(this.url, msg, this.data);
        }
    });   
}




function addIcon(sIcon)
{
    return "<span class=\"ui-icon " + sIcon + " float_class\"></span>";
}

function setupRadioTextBoxes(ElemID)
{    
    //find each radio box that has a text box tacked on
    //on clear it's value so we don't have bad data
    jQuery.each(document.getElementsByName(ElemID), function(index, item) {
        if (item.value != $("input[name="+ElemID+"]:checked").val())
        {
            if ($("#"+item.id + "_text").length > 0)
            {
                $("#"+item.id + "_text").val("");
                $("#"+item.id + "_text").addClass("ui-state-disabled");
                $("#"+item.id + "_text").attr("disabled","disabled"); 
            }                        
        }
        else
        {
            if ($("#"+item.id + "_text").length > 0)
            {
                $("#"+item.id + "_text").removeClass("ui-state-disabled");
                $("#"+item.id + "_text").removeAttr("disabled");      
            }      
        }     
    });
    
}

function makeInput(sAutoHelpId, sHelp, sId, sName, sType, bDisabled, sClass, sValue, sLabel)
{   
    var sDisabled = "";
    
    if (bDisabled)
        sDisabled = "DISABLED";
    
    var sinput = "<input id=\"" + sId + "\" name=\"" + sName + "\" type=\"" + sType + "\" "+ sDisabled +" class=\"" + sClass + "\" value=\"" + sValue + "\"></input>";    
    var slbl = hasValue(sLabel) ? "<label for=\"" + sId + "\" name=\"" + sName + "_label\">" + sLabel + "</label>" : "";     
    
    return slbl + sinput;
}

//function makeSSNInput(sAutoHelpId, sHelp, sId, sName, sType, bDisabled, sClass, sValue, sLabel, validator) {
//    var sDisabled = "";
//    
//    if (bDisabled)
//        sDisabled = "DISABLED";
//    
//    var sinput = "<input id=\"" + sId + "\" name=\"" + sName + "\" type=\"" + sType + "\" "+ sDisabled +" class=\"" + sClass + "\" value=\"" + sValue + "\" maxlength=\"" + 11 + "\" onchange=\"" + validator + "\" ></input>";    
//    var slbl = hasValue(sLabel) ? "<label for=\"" + sId + "\" name=\"" + sName + "_label\">" + sLabel + "</label>" : "";     
//    
//    return slbl + sinput;
//    var
//}

function makeMultiInput(sAutoHelpId, sHelp, sId, sName, sType, bDisabled, sClass, sValue, sLabel, sDelimiter, iPosition, iLength)
{    
    var sDisabled = "";
    var sRetValue = "";
    var labelDivClass = "";
    var sdelimiter = "";
    
    if (bDisabled)
        sDisabled = "DISABLED";
    
    var sinput = "<input id=\"" + sId + "\" name=\"" + sName + "\" type=\"" + sType + "\" "+ sDisabled +" class=\"" + sClass + "\" value=\"" + sValue + "\"></input>";    
        
    if (iPosition == iLength - 1) {
        sdelimiter = "";
        labelDivClass = "<div class=\"gft-multi-input-label-long\">"; 
    }
    else {
        sdelimiter = hasValue(sDelimiter) ? "<span class=\"gft-delimiter\">" + sDelimiter + "</span>" : "";
        labelDivClass = "<div class=\"gft-multi-input-label\">";
    }

    var slbl = hasValue(sLabel) ? labelDivClass + sLabel + "</div>" : "";
    
    if (gftApp._language == "ar-ae")
        sRetValue = "<div class=\"gft-multi-input\">" + sdelimiter + sinput + slbl + "</div>";
    else
        sRetValue = "<div class=\"gft-multi-input\">" + sinput + sdelimiter + slbl + "</div>";
        
    
    return sRetValue;
}

function writeInput(questionContainerID, sInput)
{
    $("#" + questionContainerID).append(""+ sInput +"");
}

function hasAttribute(sToCompare, sAttribute)
{
    return ( (hasValue(sToCompare) ? sToCompare : "").indexOf(sAttribute) > -1 );
}

/*******************************************************************************************
** Begin Database Defined Functions
**
**  All functions should be in the format:
**          function name(parm1, parm2, parm3, sExtra)
**
** sExtra are extra parameters defined inside MatchTextValue which can look like: 
**          <function_name> OR <function_name>|<parm>,<parm>,<n>
*******************************************************************************************/
/* These functions will appear in tblQuestionLink.MatchTextValue */
function todayStr(parm1, parm2, parm3, sExtra) {
    var today="";
    
    $.ajax({
        data: "{}",
        url: "Application.asmx/GetDate",          
        async: false,
        success: function(response) {
            var data = eval('(' + response.d + ')');
            today = data;
        },
        error: function(msg) {           
            ajaxError(this.url, msg, this.data);
        }            
    }); 
    
    return today;
}

function getReferringPartyName(parm1, parm2, parm3, sExtra) {
    return gftApp.getReferringPartyName();
}

function getQuestionValue(parm1, parm2, parm3, sExtra) {   
    var val = gftApp.verifyApplicantResponse(sExtra);
    return hasValue(val[0]) ? val[0] : "";
}

function getApplicationProperty(parm1, parm2, parm3, sExtra) {
    var val = eval("gftApp._appProps." + sExtra);
    if( $.isArray(val)){
        return hasValue(val[0]) ? val[0] : "";
    } else {
        return hasValue(val) ? val : "";
    }
}

function isValueGreaterThan(a, intVal, txtVal, sExtra, oItem) {
    if (!hasValue(a))
        return false;
    
    if (oItem.AnswerTypeName == "MultiText" || oItem.AnswerTypeName == "MultiNumber" || oItem.AnswerTypeName == "Phone")
    {
        //sExtra is which field in the multitext/multinumber to verify against
        if (isNaN(sExtra))
            sExtra = 0;
        
        //go find the control we need based on the sExtra tag and the answertypename
        a = $("#answer_"+ oItem.QuestionID + "_" + oItem.QuestionGroupID + "_" + oItem.AnswerTypeName.toLowerCase() + "_" + sExtra.toString()).val();
    }
    
    if ( hasValue(intVal) )
        return parseInt(a) > parseInt(intVal);
    else
        return a > txtVal;
}

function isValueLessThan(a, intVal, txtVal, sExtra, oItem) {
    if (!hasValue(a))
        return true;
    
    if (oItem.AnswerTypeName == "MultiText" || oItem.AnswerTypeName == "MultiNumber")
    {
        //sExtra is which field in the multitext/multinumber to verify against
        if (isNaN(sExtra))
            sExtra = 0;
            
        //go find the control we need based on the sExtra tag and the answertypename
        a = $("#answer_"+ oItem.QuestionID + "_" + oItem.QuestionGroupID + "_" + oItem.AnswerTypeName.toLowerCase() + "_" + sExtra.toString()).val();   
    }
   
    if ( hasValue(intVal) )
        return parseInt(a) < parseInt(intVal);
    else
        return a < txtVal;
}

function isValueEqualTo(a, intVal, txtVal, sExtra, oItem) {

    //account for checkbox groups which are a CSV string
    //if the checkbox is NOT a group checkbox, then you 
    //can use the MatchIntValue.
    //If the checkbox IS a group checkox, then you
    //must use MatchTextValue and you must have a "," after
    //the first value if there is only one value you are looking for
    
    if (typeof a == "string" && a.split(gftae_delimiter).length > 1)
    {
        return $.inArray(txtVal,a.split(gftae_delimiter)) != -1;
    }
    else
    {
        if (oItem.AnswerTypeName == "MultiText" || oItem.AnswerTypeName == "MultiNumber")
        {
            if (isNaN(sExtra))
                sExtra = 0;
            
            a = a.split(gftae_delimiter)[parseInt(sExtra)];    
        }
        
        if ( hasValue(intVal) )
            return parseInt(a) == parseInt(intVal);
        else
            return a == txtVal;
    }
}

//Return whether the Answer to some other question is equal to some value "a"
// this function can return a boolean OR can return a value defined in ActionIntValue
function isOtherValueEqualTo(a, intVal, txtVal, sExtra, oItem)
{
    var isEqual = isValueEqualTo(getQuestionValue(null, null, null, sExtra), intVal, txtVal, sExtra, oItem);

    if ( hasValue(oItem.ActionIntValue) )
    {
        if ( isEqual )    
            return oItem.ActionIntValue;
        else        
            return 0;
    }
    else
        return isEqual;
}

function isOtherValueNotEqualTo(a, intVal, txtVal, sExtra, oItem)
{
    var isNotEqual = isValueNotEqualTo(getQuestionValue(null, null, null, sExtra), intVal, txtVal, sExtra, oItem);

    if ( hasValue(oItem.ActionIntValue) )
    {
        if ( isNotEqual )    
            return oItem.ActionIntValue;
        else        
            return 0;
    }
    else
        return isNotEqual;
}

//Return whether a property of this application is equal to a value
function isApplicationPropertyEqualTo(a, intVal, txtVal, sExtra, oItem)
{
    var isEqual = isValueEqualTo(getApplicationProperty(null, null, null, sExtra), intVal, txtVal, sExtra, oItem);

    if ( hasValue(oItem.ActionIntValue) )
    {
        if ( isEqual )    
            return oItem.ActionIntValue;
        else        
            return 0;
    }
    else
        return isEqual;
}

//Return whether a property of this application is equal to a value
function isApplicationPropertyNotEqualTo(a, intVal, txtVal, sExtra, oItem)
{
    var isNotEqual = isValueNotEqualTo(getApplicationProperty(null, null, null, sExtra), intVal, txtVal, sExtra, oItem);

    if ( hasValue(oItem.ActionIntValue) )
    {
        if ( isNotEqual )    
            return oItem.ActionIntValue;
        else        
            return 0;
    }
    else
        return isNotEqual;
}   

function isValueNotEqualTo(a, intVal, txtVal, sExtra, oItem) 
{    
    //account for checkbox groups which are a CSV string
    //if the checkbox is NOT a group checkbox, then you 
    //can use the MatchIntValue.
    //If the checkbox IS a group checkox, then you
    //must use MatchTextValue and you must have a "," after
    //the first value if there is only one value you are looking for
    if (typeof a == "string" && a.split(gftae_delimiter).length > 1)
    {
        return $.inArray(txtVal,a.split(gftae_delimiter)) == -1;
    }
    else
    {
        if (oItem.AnswerTypeName == "MultiText" || oItem.AnswerTypeName == "MultiNumber")
        {
            if (isNaN(sExtra))
                sExtra = 0;
            
            a = a.split(gftae_delimiter)[parseInt(sExtra)];    
        }
        
        if ( hasValue(intVal) )
            return parseInt(a) != parseInt(intVal);
        else
            return a != txtVal;
    }
}

function isAnswerNull(a, intVal, txtVal) 
{
    if ( !hasValue(a) )
        return true;
    else
        return false;
}

/* determine if a tblQuestionLink.MatchTextValue is a function */
function isFunction(sText)
{   
    if (!hasValue(sText))
        return false;
        
    var sFunction;
    
    if ( sText.split("|").length > 1 )
        sFunction = sText.split("|")[0];
    else
        sFunction = sText;
    
    sFunction = sFunction.replace("Or","").replace("And","");    
    
    try
    {
        if ( typeof eval(sFunction) == "function" )
            return true;
        else
            return false;
    }
    catch(er)
    {
        return false;
    }
}

function getCountryCode(parm1, parm2, parm3, sExtra, oItem)
{
    var retValue = "";
    var country_id;
    var countryInput = "#answer_" + oItem.QuestionID + "_" + oItem.QuestionGroupID;
    
    if ($(countryInput).length > 0)
    {
        country_id = $(countryInput).val();
    }
    else
    {
        country_id = getQuestionValue(parm1, parm2, parm3, sExtra);
    }
    
    $.ajax({        
        data: "{country_id:'" + country_id +
              "'}",
        url: "Application.asmx/GetCountryCode",        
        async: false,
        success: function(response) {
            var data = eval('(' + response.d + ')');
            retValue = data;                        
        },
        error: function(msg) {           
            ajaxError(this.url, msg, this.data);            
        }            
    }); 
          
    return retValue;
}

function GetCountryRegion(parm1, parm2, parm3, sExtra) {   
    var retValue = "";
    
    $.ajax({        
        data: "{country_id:'" + parm1 +              
              "'}",
        url: "Application.asmx/GetCountryRegion",        
        async: false,
        success: function(response) {
            var data = eval('(' + response.d + ')');
            retValue = data;                        
        },
        error: function(msg) {           
            ajaxError(this.url, msg, this.data);            
        }            
    }); 
          
    return retValue.toUpperCase();
}

function GetCountryApplicationUrl(parm1, parm2, parm3, sExtra) {   
    var retValue = "";
    
    $.ajax({
    data: "{country_id:'" + parm1 +
          "', countryRegion:'" + parm2 +            
              "'}",
        url: "Application.asmx/GetCountryApplicationUrl",        
        async: false,
        success: function(response) {
            var data = eval('(' + response.d + ')');
            retValue = data;
        },
        error: function(msg) {           
            ajaxError(this.url, msg, this.data);
        }            
    }); 
          
    return retValue;
}

/* execute a tblQuestionLink.MatchTextValue defined function */
function executeFunction(oItem, val)
{   
    var sFunction;
    var sParms;
    var sEmpty = "";
    
    var matchInt = !hasValue(oItem.MatchIntValue) ? sEmpty.split("|") : oItem.MatchIntValue.toString().split("|");
    var matchText = !hasValue(oItem.MatchTextValue) ? sEmpty.split("|") : oItem.MatchTextValue.split("|");
    var sText = oItem.ActionTextValue;
    
    if ( sText.split("|").length > 1 )
    {
        sFunction = sText.split("|")[0];
        sParms = sText.split("|")[1];
    }
    else
    {
        sFunction = sText;
        sParms = null;
    }
    
    var sParmArray;
    var sOfEvals = "";
    var v;
    var bInputFound = false;
    var dbValue
    var isOr = false;
        
    if (sFunction.indexOf("Or") != -1 || sFunction.indexOf("And") != -1)
    {    
       if (sFunction.indexOf("Or") != -1)
       {   
            sFunction = sFunction.replace("Or", "")
            isOr = true;
       }
       else
       {            
            sFunction = sFunction.replace("And", "");
            isOr = false;
       }
       
       sParmArray = sParms.split(";");

       for (var cnt=0;cnt<sParmArray.length;cnt++)
       {             
            sOfEvals += (eval(sFunction)(getInputValue(sParmArray[cnt]), matchInt[cnt], matchText[cnt], sParmArray[cnt], oItem)).toString();
            if (cnt < sParmArray.length-1)
            {
                sOfEvals += isOr ? "||" : "&&";
            }
       }
       v = eval(sOfEvals);
    }
    else
    {
       v = eval(sFunction)(val, matchInt[0], matchText[0], sParms, oItem);
    }
        
    return v;
}

function addRequired(oItem)
{    
    var qstItem = $(oItem).attr("id").split("_")[1];
    var rq = "#"+qstItem;    
    $("#" + qstItem + " label").addClass("required");
    $(oItem).rules("add", "required");
}

function getQuestionRequired(questionId)
{
    var required = "None";
    
    $.ajax({
        data: "{questionId:'" + questionId +        
              "'}",
        url: "Application.asmx/GetQuestionRequired",          
        async: false,
        success: function(response) {
            var data = eval('(' + response.d + ')');
            required = data;
        },
        error: function(msg) {           
            ajaxError(this.url, msg, this.data);
        }            
    }); 
    
    return required;
}

function removeRequired(oItem)
{    
    var qstItem = $(oItem).attr("id").split("_")[1];        
    var rq = "#"+qstItem;
    $("#" + qstItem + " label").removeClass("required");    
    $(oItem).rules("remove", "required");
}

/* translation */
var transXML;
function loadCommonTranslations()
{        
    $.ajax({
    type: "GET",
    url: "../translate/common.xml",
    async: false,
    dataType: "xml",
        success: function(xml) {
            transXML = xml;  
        }
    });
}


function translate(word)
{
    var translation = "";

    if (typeof(gftApp)!== 'undefined') {
        var language = (hasValue(gftApp._language) ? gftApp._language : "en-us");
    }
    else {
        var language = "en-us";
    }

    if (typeof (transXML) == 'undefined') {
        loadCommonTranslations();
    }

    $(transXML).find("phrase").each(function() {         
        if ( $(this).attr("name") == word )
        {
            $(this).find("text").each(function() {
            
                if ($(this).attr("lg") == language)
                {                    
                    translation = $(this).text(); 
                    return false;
                }
                return true;   
            });
            
            return false;            
        }
        return true;
                
    });
        
    
    //if there is no translation get the english
    if (!hasValue(translation))
    {       
       $(transXML).find("phrase").each(function() {         
        if ( $(this).attr("name") == word )
        {
            $(this).find("text").each(function() {
            
                if ($(this).attr("lg") == "en-us")
                {                    
                    translation = $(this).text(); 
                    return false;
                }
                return true;   
            });
            
            return false;            
        }
        return true;
                
        });
    }

    //do any custom replacements
    //Any text formatted as {{sometexthere}} will attempt to evaluate
    //as a function
    
    if (hasValue(translation))
    {
        var matches = translation.match(/{{.*}}/g);

        if (hasValue(matches))
        {
            jQuery.each(matches, function(index, item) {        
                translation = translation.replace( item, eval("gftApp._appProps."+ this.replace("{{", "").replace("}}", "")) );
            });
        }
    }
    else
    {
        translation = word;
    }
    return translation;
}

function inQueue(value)
{
    var i;
	for (i=0; i < gftApp._actionQueue.length; i++) {
		if (gftApp._actionQueue[i].QuestionLinkID === value) {
			return true;
		}
	}
	return false;
}
    
/* @projectDescription jQuery Serialize Anything - Serialize anything (and not just forms!)
 * @author Bramus! (Bram Van Damme)
 * @version 1.0
 * @website: http://www.bram.us/
 * @license : CC 3.0 BY-SA
*/
(function($) {
	$.fn.serializeAnything = function() {
		var toReturn	= [];
		var els		 = $(this).find(':input').get();
		$.each(els, function() {
			//if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
			if (this.name && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
				var val = $(this).val();
				toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
			}
		});
		return toReturn.join("&").replace(/%20/g, "+");
	}
})(jQuery);

function makePrivate()
{
    bakeCookie();
    gftApp.showApplicationInformation();
}

function makePublic()
{
    expireCookie();
    gftApp.showApplicationInformation();
}

function expireCookie()
{
    $.cookie("gftae_application", "", { expires: -1 });
}

function bakeCookie()
{
    $.cookie("gftae_application", gftApp._applicationId, { expires: 365 });
}

function getCookieValue()
{
    return $.cookie("gftae_application");
}

var appEngineVersion;
function getApplicationEngineVersion()
{           
    $.ajax({ 
        data: "{}",
        url: "Application.asmx/GetApplicationEngineVersion",          
        async: false, //we need to do this synchronously.       
        success: function(response) {
            var data = eval('(' + response.d + ')');            
            if (data.length > 0) 
            {
                appEngineVersion = data;
            }
            else
            {
                appEngineVersion = "1.x";
            }
        },
        error: function(msg) {
            //ajaxError(this.url, msg, this.data);
        }
    });

    return appEngineVersion;
}   


function toggleStyleSheets()
{
    //determine which stylesheet to use
    if (gftApp._language == "ar-ae" || $.query(document.location.href).language == "ar-ae")
    {
        $.stylesheetSwitch("gftae_style_right");
    }
    else
    {
        $.stylesheetSwitch("gftae_style");
    }
}

function getInputToBindTo(answerElemId, answerTypeName)
{
    //if this is a multifield then assigne the rule to the first field
    //by default, in most cases this is the one we want to check against
    switch(answerTypeName)
    {
        case "MultiNumber":
        case "MultiText":
        case "MultiDate":
        case "Phone":
            answerElemId += "_" + answerTypeName.toLowerCase() + "_0";
            break;
            
        default:
        
            break;
    }
    
    //if this is a radio/checkbox we need to bind to the group
    //of of inputs which requires us to use it's name instead of ID
    if ($("input[name="+answerElemId+"]").length > 0)
    {
        inputToBindTo = "input[name="+answerElemId+"]";
    }
    else
    {
        inputToBindTo = "#"+answerElemId;
    }
    
    return inputToBindTo;
}

function getOnScreenInputValue(inputID)
{
    if ($(inputID).attr("type") == "radio" || $(inputID).attr("type") == "checkbox")
    {
        return $(inputID+":checked").val();
    }
    else
    {
        return $(inputID).val();
    }
}

function getInputValue(QuestionIDAndGroupID)
{
    inputID = "answer_" + QuestionIDAndGroupID;
    
    var inputValue = null;
    var isInputOnScreen = false;
    var sInput = "";
    
    if ( $("input[name="+inputID+"]").length > 0 )
    {
        sInput = "input[name="+inputID+"]";
        inputValue = getOnScreenInputValue(sInput);
        isInputOnScreen = true;
    }
    else if ( $("#"+inputID).length > 0 ) //dropdown list
    {
        sInput = "#"+inputID;
        inputValue = getOnScreenInputValue(sInput);
        isInputOnScreen = true;
    } 
   
    if (!isInputOnScreen && !hasValue(inputValue))
    {
        inputValue = gftApp.verifyApplicantResponse(inputID.split("_")[1])[0];
    }
            
    return inputValue;
}

function viewW8(applicationId)
{
    var date = new Date();
        
    gftApp.saveApplicationStep();
    window.open("DisplayOutput.aspx?tm=" + date.getTime().toString() + "&applicationid="+applicationId, "w8window");
}

function getAffiliateImage(applicationid, aid)
{
    var retValue = "";
    
    $.ajax({        
        data: "{applicationId:'" + applicationid + 
              "', advertiserId:'" + aid +              
              "'}",
        url: "Application.asmx/getAffiliateImage",        
        async: false,
        success: function(response) {            
            var data = response.d;
            retValue = data;                        
        },
        error: function(msg) {           
            ajaxError(this.url, msg, this.data);            
        }            
    }); 
          
    return retValue;
}

//clear the values of all inputs that are children
//of the specified element. We should only run this if
//the application has completely loaded and all
//actions have made their initial run.
function clearInputsInElement(elementId)
{
    if (gftApp._actionsInitialized)
    {
        jQuery.each($("#" + elementId + " input, #" + elementId + " textarea, #" + elementId + " select"), function(index, item) {                   
            switch(this.type)
            {
                case 'password':
                case 'select-multiple':            
                case 'text':
                case 'textarea':
                    $(this).val("");
                    break;
                case 'select-one':
                    $(this).val("0");
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;           
            }
        });
    }
}

function viewPDFApplication()
{   
    ajaxWorking();
    $("#jQueryAjaxWorking").dialog("open");
    $.ajax({ 
        data: "{'applicationId':'" + gftApp._applicationId + "'}",
        url: "Application.asmx/ExportCompletedApplicationToPDF",
        async: false,        
        success: function(response) {        
            window.open(location.href.substring(0,location.href.lastIndexOf('/')+1) + "output/user/" + gftApp._applicationId + ".pdf");
            $("#jQueryAjaxWorking").dialog("close");
        },
        error: function(msg) {
            $("#jQueryAjaxWorking").dialog("close");
            ajaxError(this.url, msg, this.data);
        }
    });   
}

/**
* Stylesheet toggle variation on styleswitch stylesheet switcher.
* Built on jQuery.
* Under an CC Attribution, Share Alike License.
* By Kelvin Luck ( http://www.kelvinluck.com/ )
**/

(function($)
	{
		// Local vars for toggle
		var availableStylesheets = [];
		var activeStylesheetIndex = 0;
		
		// To loop through available stylesheets
		$.stylesheetToggle = function()
		{
			activeStylesheetIndex ++;
			activeStylesheetIndex %= availableStylesheets.length;
			$.stylesheetSwitch(availableStylesheets[activeStylesheetIndex]);
		};
		
		// To switch to a specific named stylesheet
		$.stylesheetSwitch = function(styleName)
		{
			$('link[@rel*=style][title]').each(
				function(i) 
				{
					this.disabled = true;
					if (this.getAttribute('title') == styleName) {
						this.disabled = false;
						activeStylesheetIndex = i;
					}
				}
			);
			createCookie('style', styleName, 365);
		};
		
		// To initialise the stylesheet with it's 
		$.stylesheetInit = function()
		{
			$('link[@rel*=style][title]').each(
				function(i) 
				{
					availableStylesheets.push(this.getAttribute('title'));
				}
			);
			var c = readCookie('style');
			if (c) {
				$.stylesheetSwitch(c);
			}
		};
	}
)(jQuery);

// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name,"",-1);
}
// /cookie functions

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function appendParamToAnchors( selector, param, value ){
    var anchors = $(selector);

    anchors.each(function () {
        var href = this['href'].split('?');

        // initialize query param section or add &
        if (href[1] == null) {
            href[1] = "";
        } else {
            if (href[1].charAt(href[1].length - 1) != '&') {
                href[1] += "&";
            }
        }
        href = href.join('?');

        href += param + "=" + value;
        this['href'] = href;
    });
}

