﻿var intervalId;
var input_Zipcode
var input_Name
var input_PhoneNum
var input_Email

// Logic Variables:
var iZipLen
var div_content
var iZip
var bZipError
var bFormError
var errorText
var sActionKey
var sTempS
var sBranch
var outputVar
var sRoute
var input_Zipcode
var tempVideo
var $videoDialog

var videoDialogOptions = { autoOpen: false, modal: true, draggable: false, resizable: false, title: '', width: 882, height: 700,
    open: function (event, ui) {
        $(".ui-dialog").css("padding", "0px");
        $(".ui-widget-content").css({ background: 'none', border: 'none' });
    },
    close: function (event, ui) {
        $("#video").remove();
    }
};

var addthis_config = {
    data_ga_property: 'UA-25705908-1'
};


function GetAddThisButtons(url, title) {
    var addthis = "<script type=\"text/javascript\">var addthis_share = { url_transforms: { add: { video: " + window.location.href + "?video=" +
            url + ", title: " + title + "}}}</script>";
    return addthis;
}

function archiveSelectChanged() {
    var value = $('#archiveSelect').attr('value');
    window.location.hash = value;
}

function VideosSetup() {
    $videoDialog = $('#videoUrlContent').dialog(videoDialogOptions);
    $('.videoLink').click(function () {
        $("#videoUrlContent").html("<div id=\"video\" style=\"width: 882px;\"><iframe frameBorder='0' scrolling='no' class='video_landing_content' src=" + this.href + "></iframe></div>");
        $videoDialog.dialog('open');
        return false;
    });
}

function CheckVideoUrl() {
    var url = GetQueryStringValue('video');
    if (url != '') {
        $("#videoUrlContent").html("<div id=\"video\" style=\"width: 882px;\"><iframe frameBorder='0' scrolling='no' class='video_landing_content' src=" + unescape(url) + "></iframe></div>");
        $videoDialog.dialog('open');
    }
}

function GetQueryStringValue(variable) {
    var value = '';
    if (window.location.search.indexOf(variable) != -1) {
        var begin = window.location.search.indexOf(variable + '=') + 1;
        var end = (window.location.search.indexOf('&') != -1) ? window.location.search.indexOf('&') : window.location.search.length;
        var value = window.location.search.slice(begin + variable.length, end);
    }
    return value;
}

function EmailComments() {
    $('#commentsDialogTable').css('display', 'none');
    $('#commentsThanks').css('display', 'block');

    var name = $('#name').attr('value');
    if ($.trim(name) == '')
        name = 'no value provided';

    var email = $('#email').attr('value');
    if ($.trim(email) == '')
        email = 'no value provided';

    var comments = $('#comments').attr('value');
    if ($.trim(comments) == '')
        comments = 'no value provided';

    SendEmail('listening,' + name + ',' + email + ',' + comments, '');
}

function ValidateCommentsForm() {
    var name = $.trim($("#name").attr('value')) != '';
    var email = $.trim($("#email").attr('value')) != '';
    var comments = $.trim($("#comments").attr('value')) != '';
    if (name && email && comments) {
        $("#commentSubmitButton").attr('disabled', '');
    }
    else {
        $("#commentSubmitButton").attr('disabled', 'disabled');
    }
}

function EmailCallback(arg, context) {
    //    if (arg != ''){
    //        alert(arg);
    //    }
}

function setUpDialog() {

    var $dialog = $('<div id=\'emailSignup\'></div>')
			.load('/Email_Signup.html')
			.dialog({ autoOpen: false,
			    modal: true,
			    title: 'Sign up for our newsletter',
			    open: function (event, ui) {
			        $('#emailSignup').css('background-image', "url('/Images/bg_dialog_boxes.jpg')");
			    }
			});

    $('#Email_Signup_Button').click(function () {
        $dialog.dialog('open');
        return false;
    });


    var $zipDialog = $('#dialog_BAC').dialog({ autoOpen: false,
        modal: true,
        title: 'Become a Customer',
        open: function (event, ui) {
            $('#dialog_BAC').css('background-image', "url('/Images/bg_dialog_boxes.jpg')");
        },
        beforeClose: function (event, ui) {
            $('#thankYouScreen').css({ display: 'none' });
            $('#userScreen').css({ display: 'none' });
            $('#BAC_content').css({ display: 'block' });
            $('#zipcode').attr('value', 'Zip Code');
        }
    });

    $('#becomeCustomer').click(function () {
        $zipDialog.dialog('open');
        return false;
    });

}

function checkQueryString() {
    var url;
    if (window.location.search.indexOf('main=true') != -1) {
        var url = window.location.href.replace('?main=true', '');
        window.location.href = url;
    }
    else if (window.location.search.indexOf('result=success') != -1) {
        $('<div></div>')
			.load('/Success.html')
			.dialog({ modal: true, title: 'Success' });
    }
    else if (window.location.search.indexOf('result=error') != -1) {
        $('<div></div>')
			.load('/Error.html')
			.dialog({ modal: true, title: 'Error' });
    }
}

function search() {
    var term = $('#searchInput').attr('value');
    window.location = '/SearchResults.aspx?term=' + term;
}

function searchBoxEvent(event) {
    if (event.keyCode == 13) {
        search();
    }
}

function showNavigation(id) {
    if (navigator.userAgent.search('WebKit') != -1) {
        $('ul[id*="' + id + '"]').css({ display: 'inline-block' });
    }
    else {
        $('ul[id*="' + id + '"]').css({ display: 'block' });
    }
}

function hideNavigation(id) {
    $('ul[id*="' + id + '"]').css({ display: 'none' });
}

function runSlideShow(hasNavigation) {
    $('#slideshow a').css({ opacity: 0.0 });
    $('#slideshow a:first').css({ opacity: 1.0 });
    intervalId = setInterval('changeImage(' + hasNavigation + ')', 5000);
}

function changeImage(hasNavigation) {
    //if no IMGs have the show class, grab the first image
    var current = ($('#slideshow a.show') ? $('#slideshow a.show') : $('#slideshow a:first'));
    var next = ((current.hasClass('end')) ? $('#slideshow a:first') : current.next());

    //Set the fade in effect for the next image, show class has higher z-index
    //    if (next.attr('href') != '') {
    next.css({ opacity: 0.0, display: 'block' })
        .addClass('show')
        .animate({ opacity: 1.0 }, 1000);


    //Hide the current image
    current.animate({ opacity: 0.0 }, 1000, function () { current.css('display', 'none'); })
    .removeClass('show');

    if (hasNavigation) {
        var nav_current = ($('#slideshow_controls a.show') ? $('#slideshow_controls a.show') : $('#slideshow_controls a:nth-child(2)'));
        var nav_next = ((nav_current.hasClass('end')) ? $('#slideshow_controls a:nth-child(2)') : nav_current.next());

        nav_current.removeClass('show');
        nav_next.addClass('show');
        nav_current[0].children[0].src = '/Images/bttn_banner_off.jpg';
        nav_next[0].children[0].src = '/Images/bttn_banner_on.jpg';
    }
}

function gotoSlide(x) {
    clearInterval(intervalId);
    var current = ($('#slideshow a.show') ? $('#slideshow a.show') : $('#slideshow a:first'));
    var nav_current = ($('#slideshow_controls a.show') ? $('#slideshow_controls a.show') : $('#slideshow_controls a:nth-child(2)'));

    var next = $('#slideshow a:nth-child(' + x + ')');
    var nav_next = $('#slideshow_controls a:nth-child(' + (x + 1) + ')');

    //Hide the current image
    current.css({ opacity: 0.0, display: 'none' }).removeClass('show');
    nav_current[0].children[0].src = '/Images/bttn_banner_off.jpg';
    nav_current.removeClass('show');

    //Show the next image
    next.css({ opacity: 1.0, display: 'block' }).addClass('show');
    nav_next[0].children[0].src = '/Images/bttn_banner_on.jpg';
    nav_next.addClass('show');


    intervalId = setInterval('changeImage(' + true + ')', 5000);
}

function nextSlide() {
    clearInterval(intervalId);
    var current = ($('#slideshow a.show') ? $('#slideshow a.show') : $('#slideshow a:first'));
    var nav_current = ($('#slideshow_controls a.show') ? $('#slideshow_controls a.show') : $('#slideshow_controls a:nth-child(2)'));

    //Get next image, if it reached the end of the slideshow, rotate it back to the first image
    var next = ((current.hasClass('end')) ? $('#slideshow a:first') : current.next());
    var nav_next = ((nav_current.hasClass('end')) ? $('#slideshow_controls a:nth-child(2)') : nav_current.next());

    //Hide the current image
    current.css({ opacity: 0.0, display: 'none' }).removeClass('show');
    nav_current[0].children[0].src = '/Images/bttn_banner_off.jpg';
    nav_current.removeClass('show');

    //Show the next image
    next.css({ opacity: 1.0, display: 'block' }).addClass('show');
    nav_next[0].children[0].src = '/Images/bttn_banner_on.jpg';
    nav_next.addClass('show');

    intervalId = setInterval('changeImage(' + true + ')', 5000);
}

function prevSlide() {
    clearInterval(intervalId);
    var current = ($('#slideshow a.show') ? $('#slideshow a.show') : $('#slideshow a:first'));
    var nav_current = ($('#slideshow_controls a.show') ? $('#slideshow_controls a.show') : $('#slideshow_controls a:nth-child(2)'));

    //Get next image, if it reached the beginning of the slideshow, rotate it back to the last image
    var next = ((current.hasClass('first')) ? $('#slideshow a:last') : current.prev());
    var nav_next = ((nav_current.hasClass('first')) ? $('#slideshow_controls a:last').prev() : nav_current.prev());

    //Hide the current image
    current.css({ opacity: 0.0, display: 'none' }).removeClass('show');
    nav_current[0].children[0].src = '/Images/bttn_banner_off.jpg';
    nav_current.removeClass('show');

    //Show the next image
    next.css({ opacity: 1.0, display: 'block' }).addClass('show');
    nav_next[0].children[0].src = '/Images/bttn_banner_on.jpg';
    nav_next.addClass('show');

    intervalId = setInterval('changeImage(' + true + ')', 5000);
}

function hideIfEmpty() {
    $('div[id*="content_row"]').each(function (index) {
        if (jQuery.trim($(this).find('h1')[0].innerHTML) == '') {
            $(this)[0].style.display = 'none';
        }
    });
}

function changeyear(element) {
    $('#year_links a').css({ color: '' });
    element.style.color = '#717073';
}

function getDivision(varname) {
    // Load the URL into a variable
    var url = window.location.href;

    // Split the url by the ? passed var
    var url_parts = url.split("?");

    // Verify a querystring exists, return "" if not
    if (url_parts.length == 0) {
        return "";
    }

    // Then find the querystring, everything after the ?
    var query = url_parts[1];

    // Split query string into variables 
    var vars = query.split("&");

    // Set the value with "" by default
    var value = "";

    // Iterate through vars, checking each one for varname
    for (i = 0; i < vars.length; i++) {
        // Split the variable by =, which splits name and value
        var parts = vars[i].split("=");

        // Check if the correct variable
        if (parts[0] == varname) {
            // Load value into variable
            value = parts[1];

            // End the loop
            break;
        }
    }

    // Convert escape code
    value = unescape(value);

    // Convert "+"s to " "s
    value.replace(/\+/g, " ");

    // Return the value
    return value;
}

function getZip() {
    errorText = ""; // do this to prevent error on load
    // do this to prevent error if not selected:

    // Validate the form's data:  Step (1) Get the data; Step (2) Validate the data 
    inputSrc = document.getElementById('zipcode');
    input_Zipcode = inputSrc.value;

    // Prep the error text header:
    errorText = "The following fields require completion:" + "\n";
    errCount = 0;
    bFormError = false
    // Begin validating data:

    //Must Validate the Zipcode - must be all numeric:
    iZipLen = 0; // Must assign this incrementer to 0 to avoid the NaN error for open var typess
    bZipError = false;
    var sChar
    if (input_Zipcode.length > 1) {
        for (var iPos = 0; iPos <= input_Zipcode.length - 1; iPos++) {
            sChar = input_Zipcode.charAt(iPos);
            // alert("Char :" + sChar.charCodeAt());
            if (sChar >= "0" && sChar <= "9") {
                iZipLen++;
            } //alert(iZipLen);
            else {
                bFormError = true; bZipError = true; errCount = errCount + 1;
                errorText = errorText + "Please enter a valid 5 digit zip code." + "\n"; break;
            }
        }
    }

    if (iZipLen < 5 && bZipError != true) {
        bFormError = true;
        errorText = errorText + "Please enter a valid zip 5 digit code." + "\n";
    }

    // If we make it through this, get the first three characters of the zipcode:
    iZip = input_Zipcode.substr(0, 3);

    sBranch = Resolve_Zip(iZip);
    sTemp = Resolve_email(sBranch);
    sRoute = sTemp.split("|"); // STORE IT IN A FREAKIN' ARRAY! 0 = email / 1 = branch name

    //inputSrc = document.getElementById('hold_zipcode'); inputSrc.value = input_Zipcode;
    //inputSrc = document.getElementById('hold_branch_email'); inputSrc.value = sRoute[0];
    //inputSrc = document.getElementById('hold_division'); inputSrc.value = sRoute[1];

    //alert(document.getElementById('hold_division').value);

    // Test Display Data:
    //outputVar = 
    //"zipcode: " + input_Zipcode + "\n" +
    //"sBranch: " + sBranch + "\n" +
    //"email: " + sRoute[0] + "\n" +
    //"branch: " + sRoute[1];
    // alert(outputVar);

    if (bFormError)
    { document.getElementById('BAC_correction').innerHTML = errorText; }
    else {
        document.getElementById('BAC_correction').innerHTML = "";
        userScreen();
    } // move forward and get user information.
}


function userScreen() {
    div_content = "<p>Please provide your name, phone number, and email address</p>" + "\n" +
		"<p>A representative from our " + sRoute[1] + " office will contact you shortly.</p>" + "\n" +
		"<input style=\"width: 70%; margin-bottom: 5px; margin-top: 5px;\" type=\"text\" value=\"Name\" id=\"name\" name=\"name\" onclick=\"this.value=''\"/><br />" + "\n" +
		"<input style=\"width: 70%; margin-bottom: 5px; margin-top: 5px;\" type=\"text\" value=\"Phone\" id=\"phone\" name=\"phone\" onclick=\"this.value=''\"/><br />" + "\n" +
		"<input style=\"width: 70%; margin-bottom: 5px; margin-top: 5px;\" type=\"text\" value=\"Email\" id=\"email\" name=\"email\" onclick=\"this.value=''\"/><br />" + "\n" +
		"<input style=\"margin-left: 55%;\" type=\"button\" onClick=\"validateUser();\" name=\"Submit\" value=\"GO!\">"
    // Write to the next div window: 
    document.getElementById('userScreen').innerHTML = div_content;

    $('#BAC_content').css({ display: 'none' });
    $('#userScreen').css({ display: 'block' });
}

function thanksScreen() {
    //    div_content = "<p>Thank You</p>" + "\n" +
    //		"<p>We look forward to serving you.</p>"
    //    // Write to the next div window: 
    //    document.getElementById('BAC_content').innerHTML = div_content;
    $('#userScreen').css({ display: 'none' });
    $('#thankYouScreen').css({ display: 'block' });
}

function validateUser() {
    bFormError = false;
    errorText = ""; // do this to prevent error on load
    // do this to prevent error if not selected:

    // Validate the form's data:  Step (1) Get the data; Step (2) Validate the data 
    inputSrc = document.getElementById('name'); input_Name = inputSrc.value;
    inputSrc = document.getElementById('phone'); input_PhoneNum = inputSrc.value;
    inputSrc = document.getElementById('email'); input_Email = inputSrc.value;

    // Validate Name:
    if (document.getElementById('name').value == "Name") {
        bFormError = true; errCount = errCount + 1;
        errorText = errorText + "Please enter your name in the Name field." + "<br>";
    }

    if (input_Name.length < 2) {
        bFormError = true; errCount = errCount + 1;
        errorText = errorText + "Please enter your name in the Name field." + "<br>";
    }

    // Validate e-mail address
    var emailFormat = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (emailFormat.test(input_Email))
    { } // Do nothing
    else {
        errorText = errorText + "Please enter a valid email address." + "<br>";
        bFormError = true; errCount = errCount + 1;
    }


    // Verify Phone Number:
    var phoneFormat = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (phoneFormat.test(input_PhoneNum)) {
        var formattedPhoneNumber = input_PhoneNum.replace(phoneFormat, "($1) $2-$3");
        document.getElementById('phone').value = formattedPhoneNumber;
        input_PhoneNum = formattedPhoneNumber;
    }
    else {
        errorText = errorText + "Please enter a valid phone number." + "<br>";
        bFormError = true; errCount = errCount + 1;
    }


    // Test Display Data:
    outputVar = "division," + sRoute[0] + "," + input_Email + "," +
            "email: " + input_Email + "<br/><br/>" +
			"name: " + input_Name + "<br/><br/>" +
			"zipcode: " + input_Zipcode + "<br/><br/>" +
			"phone: " + input_PhoneNum + "<br/><br/>";
    //			"sBranch: " + sBranch + "<br/><br/>" +
    //			"sRoute: " + sRoute[0] + "<br/><br/>" +
    //			"sRoute: " + sRoute[1];
    SendEmail(outputVar, '');

    if (bFormError)
    { document.getElementById('BAC_correction').innerHTML = errorText; }
    else {
        document.getElementById('BAC_correction').innerHTML = errorText;
        thanksScreen();
        //alert(outputVar);
    } // move forward and get user information.

}

