/* Home Page Content Web Part
---------------------------------------------------------------*/
function hpcSwitch(Id) {
	$(".hpcBlock").css("display", "none");
	$(".content" + Id).css("display", "block");

	$(".hpcLink").removeClass("selected");
	$(".link" + Id).addClass("selected");
} 

/* Email Subscriptions
---------------------------------------------------------------*/
function checkEmailSubscriptions(csv) {
    var email = $(".txtEmail").val().replace(/^\s+|\s+$/g, "");
    if (csv != "") {
        var emails = csv.split(",");
    }
    if (email != "") {
        if (email.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
            $(".emailValidation").text("");
            if (csv != "") {
                for (var i = 0; i < emails.length; i++) {
                    if (email == emails[i]) {
                        $(".lblEmail").text($(".txtEmail").val());
                        $(".txtEmail").css("display", "none");
                        $(".lblEmail").css("display", "inline");
                        $(".lblSelections").css("display", "none");
                        $(".lblDuplicate").css("display", "inline");
                        $(".btnSignUp").css("display", "none");
                        $(".btnSaveSelections").css("display", "inline");
                        $(".chkList").attr("disabled", true);
                        return false
                    }
                }
            }
            setHidden();
            return true;
        }
        $(".emailValidation").text("Please enter a valid email.");
        return false;
    }
    $(".emailValidation").text("Email is a required field.");
    return false;
}

function setHidden() {
    var email = $(".txtEmail").val();
    $(".hiddenEmail").val(email);
    var categories = "";
    if ($(".chkList")[0] != undefined) {
        var chk = $(".chkList")[0].rows;
        for (var i = 0; i < chk.length; i++) {
            if (chk[i].children[0].children[0].checked) {
                if (chk[i].children[0].children[1].innerText != "undefined") {
                    categories += chk[i].children[0].children[1].innerText + ",";
                }
                else {
                    categories += chk[i].children[0].children[1].textContent + ",";
                }
            }
        }
    }
    $(".hiddenCategories").val(categories);
    $("#nsuwp_submit").click();
}

function selectAllNewsCategories() {
    if ($(".chkList")[0] != undefined) {
        var chk = $(".chkList")[0].firstChild.childNodes;
        for (var i = 0; i < chk.length; i++) {
            chk[i].all[1].checked = true;              
        }
    }
}

function specialCategoryChecked(id, chkClass) {
    var sender = $("#" + id);
    var chk = $("." + chkClass);
    if (sender[0].checked) {
        for (var i = 0; i < chk.length; i++) {
            if (chk[i].firstChild.id != id) {
                chk[i].firstChild.disabled = true;
                chk[i].firstChild.checked = false;
            }
        }
    }
    else {
        for (var i = 0; i < chk.length; i++) {
            if (chk[i].firstChild.id != id) {
                chk[i].firstChild.disabled = false;
            }
        }
    }
}

function newsCategoryChecked(category, chkId, txtId) {
    var chk = $("#" + chkId);
    var txt = $("#" + txtId);
    if (chk[0].checked) {
        if (txt[0].value.indexOf(category) < 0) {
            txt[0].value += category + ";#";
        }
    }
    else {
        if (txt[0].value.indexOf(category) >= 0) {
            txt[0].value = txt[0].value.replace(category + ";#", "");
        }
    }
}

function setCategoryNewsList() {
    var categories = "";
    if ($(".chkCNL")[0] != undefined) {
        var chk = $(".chkCNL")[0].rows;
        for (var i = 0; i < chk.length; i++) {
            if (chk[i].children[0].children[0].checked) {
                if (chk[i].children[0].children[1].innerText != "undefined") {
                    categories += chk[i].children[0].children[1].innerText + ",";
                }
                else {
                    categories += chk[i].children[0].children[1].textContent + ",";
                }
            }
        }
    }
    $(".hiddenCNL").val(categories);
    $("#cnlwp_submit").click();
    return true;
}

function cancelSubscription() {
    $(".txtEmail").css("display", "inline");
    $(".lblEmail").css("display", "none");
    $(".lblSelections").css("display", "inline");
    $(".lblDuplicate").css("display", "none");    
    $(".btnSignUp").css("display", "inline");
    $(".btnSaveSelections").css("display", "none");
    $(".chkList").removeAttr("disabled");
    $(".emailValidation").text("");
    tb_remove();
}

function setConfirm(email, categories) {
    $(".confirmEmail").text(email);
    var list = $(".ulCategories");
    var cats = categories.split(",");
    for (var i = 0; i < cats.length; i++) {
        if (cats[i] != "") {
            list.append("<li>" + cats[i] + "</li");
        }
    }
}

/* Content Ratings */
function rateContent(helpful) {
    var title;
    var detail;
    if (helpful == "true") {
        title = "Helpful";
        detail = "Would you like to leave a comment as well?";
        $(".chkHelpful")[0].firstChild.checked = true;
    }
    else {
        title = "Not Helpful";
        detail = "Will you help us improve our site by telling us why this page wasn't helpful?";
        $(".chkHelpful")[0].firstChild.checked = false;
    }
    $(".contentRatingTitle").text(title);
    $(".lblDetails").text(detail);
    return false;
}

function addComment() {
    $(".voteModal").css("display", "inline");
    $(".commentInput").css("display", "inline");
    $(".modalButtons").css("display", "none");
    $(".helpful_buttons").css("display", "none");
    $(".lblDetails").css("display", "none");
    $(".nsu_email").css("display", "none");
    tb_remove();
    return false;
}

function addAnother() {
    $(".voteModal").css("display", "inline");
    $(".commentInput").css("display", "inline");
    $(".modalButtons").css("display", "none");
    $(".helpful_buttons").css("display", "none");
    $(".lblDetails").css("display", "none");
    $(".nsu_email").css("display", "none");
    $(".receivedCR").css("display", "inline");
    $(".initialCR").css("display", "inline");
    $(".txtComment").val("");
    $(".nsu_subtitle").css("display", "none");
    $(".received").css("display", "none");
    tb_remove();
    return false;
}

function noComment() {
    $("#btnRateContent").click()
    tb_remove();
    return false;
}

/* Sub Header */
function changeSubHeaderColor(shClass) {
    $("#sub_header").attr("class", shClass);
}

/* What's New */
function oldNews(totalNews, dir, size) {
    var orig = 0;
    var prev;
    var start;
    var last;
    for (var i = 1; i <= totalNews; i++) {
        if ($("#news_item_" + i).hasClass("show")) {
            $("#news_item_" + i).removeClass("show");
            prev = i;
            if (orig == 0) {
                orig = i;
            }
        }
    }

    if (dir == "old") {
        start = prev + 1;
        last = start + size - 1;
        if (last > totalNews) {
            last = totalNews;
        }
    }
    else {
        start = orig - size;
        last = start + size - 1;
    }

    for (var j = start; j <= last; j++) {
        $("#news_item_" + i).removeClass("show");
        $("#news_item_" + j).addClass("show");
        if (j == start) {
            $("#news_item_" + j).addClass("borderless");
        }
    }

    if (start == 1) {
        $("#new_news").removeClass("show");
    }
    else {
        $("#new_news").addClass("show");
    }
    if (last == totalNews) {
        $("#old_news").removeClass("show");
    }
    else {
        $("#old_news").addClass("show");
    }
}


/* Forms (Mineral Certification Request, Parcel Picture on Demand)
    -- always return false to prevent postback
---------------------------------------------------------------*/
// bind click event to Area radio button
$( document ).ready( function( )
{
    if ( $( ".jq_Area :radio" ) != null && $( ".jq_Area :radio" ).length > 0 )
    {
        $( ".jq_Area :radio" )
            .click( 
                function( ) { 
                    $( ".jq_Area :radio:checked" )
                        .each( 
                            function( ) { 
                                toggleParcelQuarter( $( this ).val( ) ); /*return false;*/ } 
                            ); } );
        toggleParcelQuarter( $( ".jq_Area :radio:checked" ).val( ) );
    }

    toggleValidationHighlight( );
});


// highlight error fields
function toggleValidationHighlight( )
{
    if ( $( ".validation_error" ) != null && $( ".validation_error" ).length > 0 )
    {
        $( ".validation_error span[isvalid='true']" ).parents( "li, fieldset, .txt0, div.jq_ContactForm, div#custom_message" ).removeClass( "validation_highlight" );
        $( ".validation_error span[isvalid!='true']" ).parents( "li, fieldset, .txt0, div.jq_ContactForm, div#custom_message" ).addClass( "validation_highlight" );
    }

    // highlight captcha error state    
    $( "div.recaptcha_had_incorrect_sol div.recaptcha_input_area label.recaptcha_input_area_text span#recaptcha_instructions_error[display='none']" ).parents( "fieldset" ).removeClass( "validation_highlight" );
    $( "div.recaptcha_had_incorrect_sol div.recaptcha_input_area label.recaptcha_input_area_text span#recaptcha_instructions_error[display!='none']" ).parents( "fieldset" ).addClass( "validation_highlight" );
};

function toggleParcelQuarter( landParcelType )
{
//debugger;
    /* landParcelType
        1 == parcel
        2 == quarter
     */
    if ( landParcelType != null && landParcelType != "" )
    {
        var nestedCertArea = $( "div.nested_certification_area" );
        
        var labelArray = $( ".nested_certification_area .txt0 label.strong" );
        var textBoxArray = $( ".nested_certification_area .txt0 .txt input" );
        var rfvArray = $( ".nested_certification_area .txt0 .validation_error .jq_rfvLandTypeError" );

        if ( landParcelType == "1" || landParcelType == "2" )
        {
            // show hidden panels
            $( nestedCertArea ).attr( "style", "display: block;" );
            
            if ( landParcelType == "1" )    // parcel
            {
                // disable bundle option, and change help text
                $( ".jq_Bundle input" ).attr( "disabled", "-1" );
                $( ".jq_Bundle label" ).html( "If you want to order a Parcel Picture with this request you must choose &quot;Entire &frac14;&quot;" );
                
                // show land parcel type drop down
                $( "#landParcelType" ).attr( "style", "display: block;" );
                $( ".txtLLDCollapseFix input" ).attr( "style", "margin-left: 10px;" );
                $( ".txt:first" ).removeClass( "txtLLDCollapseFix" );

                // wire up change event to land parcel type drop down
                $( ".jq_LandType" ).change(
                    function( )
                    {
                        $( ".jq_LandType option:selected" ).each(
                            function( )
                            {
                                var landTypeSelectedText = $( this ).text( );
                                
                                if ( landTypeSelectedText == "Parcel Numbers" )
                                {
                                    $( labelArray ).text( "Parcel Number:" );
                                    $( textBoxArray ).attr( "fieldType", "parcel" );
                                    $( textBoxArray ).attr( "maxLength", "9" );
                                    
                                    $( "#fieldTypeHelpText" ).html( "" );
                                }
                                else
                                {
                                    $( labelArray ).text( landTypeSelectedText + ":" );
                                    $( textBoxArray ).attr( "fieldType", "lld" );
                                    $( textBoxArray ).attr( "maxLength", "30" );
                                    
                                    $( "#fieldTypeHelpText" )
                                        .html( 
                                            "<span>Must include Quarter, Section, Township, Range and Meridian</span>" +
                                            "<span>or Parcel, Plan</span>" + 
                                            "<span>or Lot, Block, Plan</span>" );
                                }
                            });

//                        // reset text in text boxes
//                        $( textBoxArray ).val( "" );
                    }).change( );
            
                // uncheck bundle manually
                $( ".jq_Bundle input" ).removeAttr( "checked" );
            } // end parcel
            else if ( landParcelType == "2" )   // quarter
            {
                // enable bundle option, and change help text
                $( ".jq_Bundle input" ).removeAttr( "disabled" );   // IE7/half IE8
                $( ".jq_Bundle" ).removeAttr( "disabled" );         // IE8 fix
                $( ".jq_Bundle label" ).html( "I also want to order a <span class='stronger'>Parcel Picture</span> with this request" );
                
                // hide land parcel type drop down
                $( "#landParcelType" ).attr( "style", "display: none;" );
                $( ".txt:first" ).addClass( "txtLLDCollapseFix" );
                $( ".txtLLDCollapseFix input" ).attr( "style", "margin-left: 0px;" );
                
                // change label helper text
                $( labelArray ).text( "Legal Land Description:" );
                $( textBoxArray ).attr( "fieldType", "lld" );
                $( textBoxArray ).attr( "maxLength", "30" );
                                                    
                $( "#fieldTypeHelpText" )
                    .html( 
                        "<span>Must include Quarter, Section, Township, Range and Meridian</span>" +
                        "<span>or Parcel, Plan</span>" + 
                        "<span>or Lot, Block, Plan</span>" );
            } // end quarter

        } // end if radio button selected
        else
            $( nestedCertArea ).attr( "style", "display: none;" );
    }
    
//    return false;
}; // toggleParcelQuarter


function addMoreLand( )
{
    $( "#additional_land" ).toggle( );
    $( "#additional_land_hidden" ).toggle( );
    return false;
}; // addMoreLand


function calculateRateForMineralCertification( )
{
    var errorMessage = validateTextArray( true );
    if ( errorMessage == "" )
        CalculateRate( "mineral" );
    else
        SetRateField( errorMessage );
    return false;
}; // calculateRateForMineralCertification


function calculateRateForParcelPicture( )
{
    var errorMessage = validateTextArray( true );
    if ( errorMessage == "" )
        CalculateRate( "picture" );
    else
        SetRateField( errorMessage );
    return false;
}; // calculateRateForParcelPicture


// custom validator client-side validation function for the first parcel # or lld
function validateFieldTypeTextFirst( source, args )
{
    // validate empty text
    if ( args != null && args.Value != null )
    {
	    var landType = $( ".nested_certification_area .txt0 .txt input" ).eq( 0 ).attr( "fieldType" );

	    if ( GetParcelCount( ) == 0 && GetArea( ) != "" )
            source.errormessage = ( landType == "parcel" ? "Parcel Number" : "Legal Land Description" ) + " is a required field.";
        else
            source.errormessage = "";

        args.IsValid = source.errormessage == "";
    }
    return false;
}; // validateFieldTypeTextArray


// custom validator client side validation function for the textBox array
function validateFieldTypeTextArray( source, args )
{
    // do not validate empty text
    if ( args != null && args.Value != null && args.Value != "" )
    {
        var errorMessage = validateTextArray( false );
        source.errormessage = errorMessage;
        args.IsValid = errorMessage == "";
    }
    return false;
}; // validateFieldTypeTextArray


// custom validator client side validation function for the attachment file
function validateFileExtension( source, args )
{
    if ( args != null && args.Value != null && args.Value != "" )
    {
        var fullName = args.Value;
        var splitName = fullName.split( "." );
        var fileType = splitName[ splitName.length - 1 ].toLowerCase( );
        
        // initial check to make sure no executables are uploaded
        //   (more comprehensive validation done server side)
        args.IsValid = fileType != "exe" && fileType != "dll" && fileType != "wsp";
    }
    return false;
}; // validateFileExtension


// make sure parcel numbers and llds are valid before posting the form
function validateFormSubmission( )
{
    // force all client-side validation to run
    var isValidPage = Page_ClientValidate( );// Page_ClientValidate( "vgAll" );
    
    // highlight error fields on a client-side refresh
    toggleValidationHighlight( );
    
    return isValidPage;
}; // validateFormSubmission


function validateTextArray( isCalc )
{
    var errorMessage = "";
    
	var numCount = GetParcelCount( );
	var landType = $( ".nested_certification_area .txt0 .txt input" ).eq( 0 ).attr( "fieldType" );
	var parcelNumCount = landType == "parcel" ? numCount : 0;
	var lldNumCount = landType == "lld" ? numCount : 0;

    // calculate rate messages
    var strEnterLLDs = "Enter Legal Land Descriptions.";
    var strParNumOrLLDRequired = "Enter " + ( landType == "parcel" ? "Parcel #'s" : "LLDs" ) + ".";
    
    // validation summary messages
    var strLLDRequired = "Legal Land Description is a required field.";
    var strRequired = landType == "parcel" ? "Parcel Number is a required field." : strLLDRequired;
	
	if ( isCalc && GetServiceOption( ) == "custom" )
        errorMessage = "Estimate required for custom service." ;//isCalc ? "Estimate required for custom service." : "";
	// check if the LLD
    else if ( lldNumCount == 0 && GetArea( ) == "quarter" )
        errorMessage = isCalc ? strEnterLLDs : strLLDRequired;
	// only calculate the rate if only parcel numbers or LLDs are entered
	else if ( isCalc && lldNumCount > 0 && parcelNumCount > 0 )
        errorMessage = strParNumOrLLDRequired;
	else if ( lldNumCount == 0 && parcelNumCount == 0 )
        errorMessage = isCalc ? strParNumOrLLDRequired : strRequired;
	// if the calculation is based on parcel numbers, make sure they are valid
	else if( parcelNumCount > 0 && GetBadParcelNumbers( ) > 0 )
        errorMessage = isCalc ? "Enter valid 9-digit Parcel Numbers." : "Invalid 9-digit Parcel Number.";

    return errorMessage;
}; // validateTextArray

/* End Forms
---------------------------------------------------------------*/


/* Content Rating Report */
function showHideComments(choice) {
    if (choice == "show")
        $(".td_comment").css("display", "");
    else
        $(".td_comment").css("display", "none");
}

/* Edit Email Subscription */
function checkEmailEdit(csv) {
    var email = $(".txtEmail").val().replace(/^\s+|\s+$/g, "");
    if (csv != "") {
        var emails = csv.split(",");
    }
    if (email != "") {
        if (email.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
            $(".emailValidation").text("");
            if (csv != "") {
                for (var i = 0; i < emails.length; i++) {
                    if (email == emails[i]) {
//                        $(".lblEmail").text($(".txtEmail").val());
//                        $(".txtEmail").css("display", "none");
//                        $(".btnSignUpEdit").css("display", "none");
//                        $(".lblEmail").css("display", "");
//                        $("#edit_selections").css("display", "");
//                        $(".btnSaveSelections").css("display", "");
//                        $(".btnCancelEdit").css("display", "");
//                        $(".lblSubsEditFooter").css("display", "");
                        return true;
                    }
                }
            }
            $(".emailValidation").text("Email Subscription does not exist or is not confirmed.");
            return false;
        }
        $(".emailValidation").text("Please enter a valid email.");
        return false;
    }
    $(".emailValidation").text("Email is a required field.");
    return false;
}

function TelerikOnLoad(editor) {

//    var fileref = document.createElement("link")
//    fileref.setAttribute("rel", "stylesheet")
//    fileref.setAttribute("type", "text/css")
//    fileref.setAttribute("href", "~/_layouts/ISCWebSiteStyles/Telerik/telerik.css")

//    if (editor._contentArea != null) {
//        editor._contentArea.parentNode.getElementsByTagName("head")[0].appendChild(fileref);
//    }
//    else if (editor.ContentArea != null) {
//        editor.ContentArea.parentNode.getElementsByTagName("head")[0].appendChild(fileref);
//    }
    
}

function runApp(appLink, isNewWindow, iFrameId, windowFeatures) {
    var hostName = document.location.host;
    if (hostName.indexOf('admin.') >= 0) {
        var publicHostName = hostName.replace(/admin./i, "");
        alert("This application must be run from the PUBLIC web site which is:\n\r\t\t" + publicHostName);
    }
    else {
        if (isNewWindow) {
            window.open(appLink, "", windowFeatures);
        }
        else {
            document.getElementById(iFrameId).src = appLink;
        }
    }
}

function fixEditLink(url) {
    if ($("#qaEditPage_anchor")[0] != undefined) {
        $("#qaEditPage_anchor")[0].href = url;
    }
    if ($("#siteactiontd")[0] != undefined) {
        var editMenu = $("#siteactiontd")[0].children[0].children[0].children;
        if (editMenu.length > 0) {            
            for (var i = 0; i < editMenu.length; i++) {
                if (editMenu[i].id.substr(editMenu[i].id.length - 11) == "wsaEditPage") {
                    editMenu[i].attributes["onMenuClick"].value = "javascript:(window.location='" + url + "')";
                }
            }
        }
    }
}

function setWidth() {
    //$("#jqLiquid .inner table").css('width', 'auto');
    //$("#jqLiquid .inner").css('width', 'auto');
    var first = $("#jqFirst").width();
    var liquid = $("#jqLiquid .inner").width();
    var width = first + liquid + 40;
    if (width > 961) {
        $(".doc3").css("min-width", width);
    }
}

function printLink() {
    str = "<link rel='stylesheet' type='text/css' href='/LAND/common/styles/cmn.css'>";
    str += "<link rel='stylesheet' type='text/css' href='/SEC/SecWeb/css/SecStylesheet.css'>";
    str += "<link rel='stylesheet' type='text/css' href='/LAND/css/style.css'>";
    str += "<link rel='stylesheet' type='text/css' href='/LAND/tps/styles/tps.css'>";
    str += "<img src='/_layouts/IMAGES/ISCWebSite/global/isc_logo.png' alt='' />";
    str += "<div id='printOverlay' style='position:absolute; left:0px; top:0px; width:100%; height:100%; background-image: url(/land/common/images/trans.gif); z-index:10000;'></div>";
    if(document.getElementById('landIFrame').contentDocument)  //Non-IE Browswers
	{
		str += document.getElementById('landIFrame').contentDocument.body.innerHTML;
	}
    else if (document.getElementById('landIFrame').contentWindow)  //IE
	{
		str += document.getElementById('landIFrame').contentWindow.document.body.innerHTML;
	}
    str = str.replace (/"images/gi, '"/SEC/SecWeb/IMAGES');
    str = str.replace(/..\/..\/common\/images/gi, "../../LAND/Common/images");
    OpenWindow = window.open();
    OpenWindow.document.write(str);
    OpenWindow.document.getElementById('printOverlay').style.height = OpenWindow.document.body.scrollHeight;
    OpenWindow.document.close();
}

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) // if too long...trim it!
    {
        field.value = field.value.substring(0, maxlimit);
    }
    else // otherwise, update 'characters left' counter
    {
        countfield.value = maxlimit - field.value.length;
    }
}
