// Global variables
var mobileBypass = "";
var host = document.location.hostname;
var today;
var sTime;
var userId = "";
var siteName = "";
var userName = "";
var userEmail = "";
var phone = "";
var mobilePhone = "";
var uAgent = navigator.userAgent;
if (document.location.hostname.indexOf("mobile.") != -1)
    var mobileSite = true;
else
    var mobileSite = false;

// Cookie Functions
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;
}

if (readCookie("mobileBypass")) {
    mobileBypass = readCookie("mobileBypass");
}
if (mobileBypass == "true" || document.location.search.indexOf("mb=true") != -1) {
    mobileBypass = "true";
    createCookie("mobileBypass", "true", 1);
}

// Top Nav
function topNavHover(e) {
    if ($(this).hasClass("closed") && e.type == "mouseenter") {
        setOffset(this, e.type);
        $(this).removeClass("closed");
        $(this).addClass("opened");

        if ($(this).hasClass("prodResFly")) {
            document.getElementById("prodResFlyShim").style.display = "none";
        } else if ($(this).hasClass("prodComFly")) {
            document.getElementById("prodComFlyShim").style.display = "none";
        } else if ($(this).hasClass("aboutCareersFly")) {
            //document.getElementById("aboutCareersFlyShim").style.display="none";
        } else if ($(this).hasClass("aboutNewsFly")) {
            //document.getElementById("aboutNewsFlyShim").style.display="none";
        }
    } else {
        $(this).addClass("closed");
        $(this).removeClass("opened");

        if ($(this).hasClass("prodResFly")) {
            document.getElementById("prodResFlyShim").style.display = "block";
        } else if ($(this).hasClass("prodComFly")) {
            document.getElementById("prodComFlyShim").style.display = "block";
        } else if ($(this).hasClass("aboutCareersFly")) {
            //document.getElementById("aboutCareersFlyShim").style.display="block";
        } else if ($(this).hasClass("aboutNewsFly")) {
            //document.getElementById("aboutNewsFlyShim").style.display="block";
        }
    }
}
function setOffset(topNavContainer, e) {
    var t = topNavContainer;
    var tFly = t.getElementsByTagName("TABLE")[0];
    if (t.tagName != "LI") {
        tFly.style.left = t.offsetWidth - 14 + "px";
        // come back		
        //if(parseFloat($D.getX(tFly)+tFly.offsetWidth) > parseFloat($D.getViewportWidth()))
        //	tFly.style.left = parseFloat(-tFly.offsetWidth+14)+"px";
    }
}

// Star Rating Functions
function setStars(el) {
    var elId = el.id;
    if (elId == "star5") {
        stars = $("#star1,#star2,#star3,#star4,#star5");
    } else if (elId == "star4") {
        stars = $("#star1,#star2,#star3,#star4");
    } else if (elId == "star3") {
        stars = $("#star1,#star2,#star3");
    } else if (elId == "star2") {
        stars = $("#star1,#star2");
    } else if (elId == "star1") {
        stars = $("#star1");
    }
}
function starHover(e) {
    setStars(this);
    stars.toggleClass("over");
}
function checkPageRating() {
    var thisPage = document.location.pathname;
    if (readCookie("ratedPage-" + thisPage)) {
        var savedRating = readCookie("ratedPage-" + thisPage);
        if (savedRating != "") {
            var el = document.getElementById(savedRating);
            setStars(el);
            stars.addClass("at");
        }
    }
}
function setPageRating(e) {
    var el = this;
    var rating = el.id;

    allStars = $("#star1,#star2,#star3,#star4,#star5");
    $(allStars).removeClass("at");

    setStars(el);
    stars.addClass("at");

    var ratedPage = document.location.href;
    createCookie("ratedPage-" + ratedPage, rating, 10000);

    $("#ratingConfirm").show();
    //thisEl.innerHTML = oldMan+"<div id='ratingConfirm'>Thanks for the info!</div>";
    var t = setTimeout("$('#ratingConfirm').hide();", 3000);

    rating = stars.length;
    addVisitorFeedback('', ratedPage, rating)
}
// End Star Rating Functions

// Left Nav functions
function leftNavClick(e) {
    if ($(this).hasClass("closed")) {
        $(this).addClass("opened");
        $(this).removeClass("closed");
    } else {
        $(this).addClass("closed");
        $(this).removeClass("opened");
    }
}

// Font Switcher functions
function fontSwitcher(size) {
    if (size) {
        $("#fontSm,#fontMed,#fontLrg").removeClass("at");
        $("#font" + size).addClass("at");

        $("link[id*='fontSizer']").attr("disabled", true);
        $("#fontSizer" + size).attr("disabled", false);

        createCookie("fontsize", size, 10000);
    }
}
function fontSizeRead() {
    if (readCookie("fontsize")) {
        var fontSize = readCookie("fontsize");
        fontSwitcher(fontSize);
    } else {
        $("link[id*='fontSizer']").attr("disabled", true);
    }
}

// Stock Ticker Functions
function getStockXML() {
    $.ajax({
        type: "GET",
        url: "/webservices/AjaxStreamingProxy/RegularProxy.ashx?u=" + escape("http://xml.corporate-ir.net/irxmlclient.asp?compid=233852&reqtype=quotes") + "&c=0",
        dataType: "xml",
        success: parseStockXml
    });
}
function parseStockXml(xml) {
    var stockChange = $(xml).find("Stock_Quote[Ticker*='FAF'] > Change").text();
    stockChange = (stockChange >= 0) ? "+" + stockChange : stockChange;

    if ($(xml).find("Stock_Quote[Ticker*='FAF'] > Trade").text() != "") {
        $("#fafQuote").text("FAF: " + $(xml).find("Stock_Quote[Ticker*='FAF'] > Trade").text());
        $("#stockTicker").attr("title", stockChange + "  " + $(xml).find("Stock_Quote[Ticker*='FAF'] > Date").text() + " ET");

        if (stockChange >= 0)
            $('#stockTicker').css({ 'background': 'url(/assets/images/ico-stock-up.png) right 19px no-repeat' });
        else
            $('#stockTicker').css({ 'background': 'url(/assets/images/ico-stock-down.png) right 19px no-repeat' });
    }
}

function initStockTicker() { // Init Stock Ticker Controls 
    getStockXML();
    setInterval(getStockXML, 20000);
    $("#stockTicker").bind("click", function () { location.href = "http://investors.firstam.com/phoenix.zhtml?c=233852&p=irol-stockQuote" });
}
// End Stock Ticker Functions

// Short URL Functions
function getShortURL() {

    var w = window.open(); // Open blank window to be filled after short URL is generated... this avoids some popup blockers
    w.opener = null;

    var url = document.location.href;
    var qString = "?p=jmp";
    if (url.indexOf("?") != -1)
        qString = "&p=jmp";
    $.ajax({
        type: "GET",
        url: "/webservices/AjaxStreamingProxy/RegularProxy.ashx?u=" + escape("http://api.bit.ly/v3/shorten?domain=j.mp&login=faeagle&apiKey=R_7cefe1faa7c44f741a90ad9ac2cc4d8d&longUrl=" + escape(url + qString) + "&format=txt") + "&c=0",
        dataType: "html",
        success: function (html) { shortURLSuccess(html, w); }
    });
}
function shortURLSuccess(html, w) {
    w.document.location = "http://twitter.com/home?status=" + $("h1").html().replace("<br>", " ").substring(0, 120) + " " + html + " %23FirstAmerican";
}
// End Short URL Functions

// Utility functions
function elementHover(e) {
    $(this).toggleClass("over");
}
function elementSubmitHover(e) {
    $(this).toggleClass("submitOver");
}
function elementSmallHover(e) {
    $(this).toggleClass("smallOver");
}
function elementSmallSubmitHover(e) {
    $(this).toggleClass("smallSubmitOver");
}

function elementHover(e) {
    $(this).toggleClass("over");
}
function elementExpand(e) {
    if ($(this).hasClass("at"))
        $(this).removeClass("at");
    else
        $(this).addClass("at");
}
function toggleDisplay(elId, display) {// Toggle Display of Page Elements
    var el = document.getElementById(elId).style;
    if (el.display != 'none' && display != 'show') {
        el.display = 'none';
    } else {
        el.display = '';
    }
}
function toggleClass(el, elClass) {
    if (!$(el).hasClass(elClass)) {
        $(el).addClass(elClass);
    } else {
        $(el).removeClass(elClass);
    }
}

function toggleClosedList() {
    var list = $(this).next(); //$D.getNextSibling(this);
    if ($(list).hasClass("off")) {
        $(this).addClass("opened");
        $(this).removeClass("closed");
        $(list).addClass("on");
        $(list).removeClass("off");
        this.id = "at";
    } else if ($(list).hasClass("on")) {
        $(this).addClass("closed");
        $(this).removeClass("opened");
        $(list).addClass("off");
        $(list).removeClass("on");
        this.id = "";
    }
}
function showHiddenListItems() {
    var hiddenLinks = $(this.parentNode + " .off")//D.getElementsByClassName("off","",this.parentNode);
    $(hiddenLinks).toggleClass("off");
    this.className = "off";
}
function listItemClick(e) {
    var links = this.getElementsByTagName("A");
    if (links[0]) {
        var aObj = links[0];
        if (whichElement(e).tagName != "A" && whichElement(e).parentNode.tagName != "A") {
            if (aObj.target == "_blank") {
                window.open(aObj.href);
            } else {
                document.location.href = aObj.href;
            }
        }
    }
}
function stopEvent(e) {
    e.preventDefault();
    e.stopPropagation();
}
function openWin(url, name, attr) {
    var w = window.open('', name, attr);
    w.opener = null;
    w.document.location = url;
    w.focus();
}

// These four functions return document measurements when needed
function f_clientWidth() {
    return f_filterResults(
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_scrollTop() {// Returns the user's Vertical scroll position
    return f_filterResults(
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_scrollLeft() {// Returns the user's horizontal scroll position
    return f_filterResults(
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } 
    }
}


function checkPromosDates() {
    var promos = $("#rightCol div.promo");
    var promoStart = "";
    var promoEnd = "";
    if (promos) {
        var i = 0;
        for (i = 0; i <= promos.length - 1; i++) {
            var promo = promos[i];
            if (promo.getAttribute("startdate"))
                promoStart = promo.getAttribute("startdate");
            if (promo.getAttribute("enddate"))
                promoEnd = promo.getAttribute("enddate");
            var startDate = new Date(promoStart);
            var endDate = new Date(promoEnd);

            var today = new Date();
            if ((startDate <= today || promoStart == "") && (endDate >= today || promoEnd == "")) {
                $(promo).removeClass("off");
            }
        }
    }
}

function whichElement(e) {
    var targ;
    if (!e) {
        var e = window.event;
    } if (e.target) {
        targ = e.target;
    } else if (e.srcElement) {
        targ = e.srcElement;
    } if (targ.nodeType == 3) { // defeat Safari bug
        targ = targ.parentNode;
    }
    return targ;
}

// Toggle Modal Window
function initModals() {
    var activeWin;
    var offsiteURL;

    //select all the a tag with name equal to modal
    $('a[name=modal],button[name=modal]').click(function (e) {

        e.preventDefault(); //Cancel the link behavior
        e.stopPropagation();

        if ($(this).hasClass("offsiteLink")) {//For offsite links open modal window first before opening link
            if (this.href) {
                offsiteURL = $(this).attr("offsiteurl");
            } else if (this.value == 'Continue') {
                openWin(offsiteURL, '', '');
                return true;
            }
        }

        var id = $(this).attr('href'); //Get the A tag
        activeWin = $(id);

        if ($(this).attr('id') == 'feedbackLink') {
            $(id).find('#emailTo').val('FAWebMaster' + '@' + 'firstam.com');
            $('#contactFormName').val('feedback');
            $(id).find('h4').text('Feedback');
            $(id).find('#contactPrefEmail').removeAttr('checked');
        } else if ($(this).attr('href') == '#modalContact') {
            $(id).find('#emailTo').val($(this).attr('id') + '@' + $(this).attr('domain'));
            $('#contactFormName').val('contact');
            $(id).find('h4').text($(this).text());
            $(id).find('#contactPrefEmail').attr('checked', 'checked');
        }

        var maskHeight = $(document).height(); //Get the screen height and width
        var maskWidth = $(window).width();

        $('#mask').css({ 'width': maskWidth, 'height': maskHeight }); //Set heigth and width to mask to fill up the whole screen

        $('#mask').show();

        if ($(id).find(".tl").length != 0) {
            var winH = $(window).height(); //Get the window height and width
            var winW = $(window).width();
            var winTop = winH / 2 - $(id).height() / 2 + f_scrollTop();
            var winLeft = winW / 2 - $(id).width() / 2;
            activeWin.css({ 'top': winTop, 'left': winLeft }); //Set the popup window to center

            activeWin.draggable();
        } else {
            var winTop = f_scrollTop() + 10;
            activeWin.css({ 'top': winTop }); //Set the popup window to top		
            $('#emailPage').click(function () {
                $('#modalShare').removeClass("show");
            });
        }

        activeWin.toggleClass("show");
        toggleSelect("hide");

    });

    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();

        $('#mask').hide();
        activeWin.toggleClass("show");

        toggleSelect("show");
    });

    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        activeWin.toggleClass("show");
        toggleSelect("show");
    });

}
function closeWindow(modal) {
    $('#mask').hide();
    $(modal).toggleClass("show");
    $(modal).find('.confirm').addClass('off');
    $(modal).find('form').removeClass('off');
    $(modal).find('form').removeClass('hide');
}

function gotoState(selectedState, stateCode) {
    if ($("#Map area").length != 0) {
        var mapArea = $("#Map area[name='" + selectedState + "']");
        var stateUrl = mapArea.attr("href");

        if (mapArea.attr("target") == "_blank") {
            window.open(stateUrl);
        } else {
            document.location.href = stateUrl;
        }
    } else {
        if (stateCode != "" && stateCode != "USA") {
            var sHref = "/title/" + $(':selected').val();
            document.location.href = sHref;
        }
    }
}

// Email Functions
function initEmailThisPage() {
    $("#emailPageForm").validate({
        errorPlacement: function (error, element) {
            error.insertBefore(element);
        },
        messages: {
            emailPageFromName: {
                required: 'Please enter your name.'
            },
            emailPageFrom: 'Please enter a valid email address.',
            emailPageTo: 'Please enter a valid email address.'
        },
        submitHandler: function (form) {
            var emailTo = $('#emailPageTo').val();
            var emailFromName = $('#emailPageFromName').val();
            var emailFromEmail = $('#emailPageFrom').val();
            var emailFrom = (document.location.host.indexOf('title') != -1) ? 'donotreply.title@firstam.com' : 'donotreply@firstam.com';
            var emailSubject = emailFromName + " has sent you a message from the " + siteName + " website";

            var emailGreeting = '';
            if ($("#emailPageToName").length != 0)
                emailGreeting = ($('#emailPageToName').val() != '') ? '<p>Dear ' + $('#emailPageToName').val() + ',</p>' : '';

            if ($("#emailPageCC:checked").length != 0)
                emailTo = emailTo + ',' + $('#emailPageFrom').val();

            var emailMessage = ($('#emailPageMsg').val() != '') ? '<p><b>The following message is from ' + emailFromName + ':</b><br>' + $('#emailPageMsg').val() + '</p>' : '';
            var emailBody = '<style>p{font-family:Arial, Helvetica, sans-serif; color:black; font-size:11pt}</style>' + emailGreeting + '<p>' + emailFromName + ' thought you would be interested in viewing the following page on ' + siteName + '\'s  website.</p>' + '<p><a href="' + document.location.href.replace("mobile.", "") + ' ">' + document.location.host.replace("mobile.", "") + document.location.pathname + '</a></p>' + emailMessage + '<p style="color:silver">____________________________________</p><p><img src="http://www.firstam.com/assets/email/images/email-logo.gif" alt="First American" width="211" height="53" /></p><p style="color:gray; font-size:10pt">This is a one-time email from First American. You received this email because someone requested the link to be sent to you. No future email will be sent to you unless you or someone else make a request through First American\'s website.</p>' + ' ';

            email(emailTo, emailFrom, emailSubject, emailBody, $('#modalEmailPage'), '', emailFromName, emailFromEmail, '');
        }
    });
}
function initContact() {
    $("#contactForm").validate({
        errorPlacement: function (error, element) {
            error.insertBefore(element);
        },
        messages: {
            contactName: {
                required: 'Please enter your name.'
            },
            contactEmail: 'Please enter a valid email address.'
        },
        submitHandler: function (form) {
            var emailFromName = $('#contactName').val();
            var emailFromEmail = $('#contactEmail').val();
            var phone = $('#contactPhone').val();
            var emailSubject = siteName + " website message from " + emailFromName;
            if ($('#formName').val() == 'feedback') emailSubject = siteName + " website feedback from " + emailFromName;
            var emailBody = "<style>p{font-family:Arial, Helvetica, sans-serif; color:black; font-size:11pt}</style>" +
				"<p>" + emailFromName + " was viewing the following page on the " + siteName + " website: </p>" +
				"<p><a href='" + document.location.href + "'>" + document.location.host + document.location.pathname + "</a></p>" +
				"<p><b>Message from " + emailFromName + ":</b><br>" +
					$('#contactComments').val() +
				"</p>" +
				"<p><b>Contact info:</b><br>" +
					"Name: " + emailFromName + "<br>" +
					"Email: " + emailFromEmail + "<br>" +
					"Phone: " + phone + "<br>" +
					"Contact Preference: " + $('#contactPref :checked').val() +
				"</p>" + " ";

            email($('#modalContact').find('#emailTo').val(), 'donotreply.title@firstam.com', emailSubject, emailBody, $('#modalContact'), '', emailFromName, emailFromEmail, phone); // this is for production
            //email($('#contactEmail').val(), $('#contactEmail').val(), emailSubject, emailBody, $('#modalContact')); // this one is for testing the contact gets their own email.
        }
    });
}
function email(to, from, subject, body, modal, confmsg, userName, userEmail, phone) {

    var htmlBody = encodeURIComponent(body) + "<p>- " + userName + "</p>";
    var mailSubject = encodeURIComponent(subject);

    $('#centerPage').css({ 'cursor': 'wait' });
    $.ajax({
        type: "POST",
        url: "/webservices/FirstAMEmailService/EmailService.svc/Email",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{\"to\":" + "\"" + to + "\"" + ", \"from\":" + "\"" + from + "\"" + ", \"subject\":" + "\"" + mailSubject + "\"" + ", \"body\":" + "\"" + htmlBody + "\"" + "}",
        success: function () { confirmEmail(modal, confmsg, userName, userEmail, phone) },
        error: jqueryError
    });
}

function initVcard() {
    $("#vcardForm").validate({
        errorPlacement: function (error, element) {
            error.insertBefore(element);
        },
        messages: {
            contactEmail: 'Please enter a valid email address.'
        },
        submitHandler: function (form) {
            var repName = $('#repName').text();
            var emailFromEmail = $('#contactEmail').val();
            var emailSubject = 'vCard For ' + repName + ' Attached';
            var emailBody = '<style>p{font-family:Arial, Helvetica, sans-serif; color:black; font-size:11pt}</style>' +
				'<p>The attached vCard for ' + repName + ' is sent to you from First American\'s website. You may open the attached file and save it to your contacts.</p>' +
				'<p>Visit ' + repName + '\'s webpage at:<br /><a href="' + document.location.href.replace("mobile.", "") + '">' + document.location.host.replace("mobile.", "") + document.location.pathname + '</a></p>' + '<p style="color:silver">____________________________________</p><p><img src="http://www.firstam.com/assets/email/images/email-logo.gif" alt="First American" width="211" height="53" /></p><p style="color:gray; font-size:10pt">This is a one-time email from First American. You received this email because someone requested the vCard to be sent to you. No future email will be sent to you unless you or someone else make a request through First American\'s website.</p>' + ' ';

            emailAttach($('#vcardEmail').val(), 'donotreply.title@firstam.com', emailSubject, emailBody, $('#vcardPath').val(), $('#modalVcard'), '', '', emailFromEmail, ''); // this is for production
            //email($('#contactEmail').val(), $('#contactEmail').val(), emailSubject, emailBody, $('#modalContact')); // this one is for testing the contact gets their own email.
        }
    });
}
function emailAttach(to, from, subject, body, path, modal, confmsg, userName, userEmail, phone) {
    attachmentPath = encodeURIComponent(path);
    htmlBody = encodeURIComponent(body);
    mailSubject = encodeURIComponent(subject);
    $.ajax({
        type: "POST",
        url: "/webservices/WCFEmailService/EmailService.svc/EmailAttachment",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        //data: "&to=" + to + "&from=" + from + "&subject=" + subject + "&body=" + body,
        data: "{\"to\":" + "\"" + to + "\"" + ", \"from\":" + "\"" + from + "\"" + ", \"subject\":" + "\"" + mailSubject + "\"" + ", \"body\":" + "\"" + htmlBody + "\"" + ", \"path\":" + "\"" + attachmentPath + "\"" + "}",
        success: function () { confirmEmail(modal, confmsg, userName, userEmail, phone) },
        error: jqueryError
    });
}

function jqueryError(request, status, error) {
    if (request.responseText != "") {
        //$('#modalEmailPage .error').removeClass('off');
        //$('#modalEmailPage .error').html(request.responseText);
    }
}
function confirmEmail(modal, confmsg, userName, userEmail, phone) {
    if (modal != "") {
        $('#centerPage').css({ 'cursor': 'auto' });
        $(modal).find('.confirm').removeClass('off');
        $(modal).find('.confirm').html('<label class="confirm">Your message was sent successfuly!</label>');
        $(modal).find('form').addClass("hide");
        window.setTimeout(function () { closeWindow(modal) }, 2000);
    } else {
        $('#centerPage').css({ 'cursor': 'auto' });
        $('#localStateForm').css({ 'display': 'none' });
        $('div.confirmMsg').html(confmsg);
        $('div.confirmMsg').focus();
    }
    updateUser('', userName, phone, '', userEmail, '');
}
// End Email this page Functions

// ******** User Tracking Functions *********
function addVisitorStateInfo(visitorID, state, preferredLocation, preferredRepresentation) {
    $.ajax({
        type: "GET",
        url: "/webservices/FirstAMVisitorTrackingService/VisitorTrackingService.svc/AddUpdateVisitorStateInfo",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "&visitorID=" + visitorID + "&state=" + state + "&preferredLocation=" + preferredLocation + "&preferredRepresentation=" + preferredRepresentation,
        error: jqueryError
    });
}
function addVisitorPageHistory(visitorID, pageLocation) {
    $.ajax({
        type: "GET",
        url: "/webservices/FirstAMVisitorTrackingService/VisitorTrackingService.svc/AddVisitorPageHistory",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "&visitorID=" + visitorID + "&pageLocation=" + pageLocation,
        error: jqueryError
    });
}
function addVisitorMiscInfo(visitorID, name, value) {
    $.ajax({
        type: "GET",
        url: "/webservices/FirstAMVisitorTrackingService/VisitorTrackingService.svc/AddVisitorMiscInfo",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "&visitorID=" + visitorID + "&name=" + name + "&value=" + value,
        error: jqueryError
    });
}
function addVisitorFeedback(userId, pageLocation, rating) {
    if (userId != "") {
        userId = userId;
        var dbGenUser = true;
    } else {
        if (readCookie("userId"))
            userId = readCookie("userId");
        var dbGenUser = false;
    }

    if (userId != "") {
        $.ajax({
            type: "GET",
            url: "/webservices/FirstAMVisitorTrackingService/VisitorTrackingService.svc/AddVisitorFeedback",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "&visitorID=" + userId + "&pageLocation=" + pageLocation + "&rating=" + rating,
            error: function () { if (dbGenUser == false) addNewUser('', '', '', '', '', pageLocation, rating); else jqueryError; }
        });
    } else {
        addNewUser('', '', '', '', '', pageLocation, rating);
    }
}
function updateUser(userId, userName, phone, mobilePhone, userEmail, role) {
    if (userId != "") {
        userId = userId;
        var dbGenUser = true;
    } else {
        if (readCookie("userId"))
            userId = readCookie("userId");
        var dbGenUser = false;
    }

    if (userId != "") {
        $.ajax({ // Get user info from DB and assign to variables
            type: "GET",
            url: "/webservices/FirstAMVisitorTrackingService/VisitorTrackingService.svc/GetVisitorData",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "&visitorID=" + userId,
            success: function (result) {
                var cUserName = (result.Name) ? result.Name : "";
                var cPhone = (result.OfficePhone) ? result.OfficePhone : "";
                var cMobilePhone = (result.MobilePhone) ? result.MobilePhone : "";
                var cUserEmail = (result.Email) ? result.Email : "";
                var cRole = (result.RoleSpecified) ? result.RoleSpecified : "";

                var qUserName = (userName.length >= cUserName.length) ? "&name=" + escape(userName) : "&name=" + escape(cUserName);
                var qPhone = (phone != "") ? "&officePhone=" + escape(phone) : "&officePhone=" + escape(cPhone);
                var qMobilePhone = (mobilePhone != "") ? "&mobilePhone=" + escape(mobilePhone) : "&mobilePhone=" + escape(cMobilePhone);
                var qRole = (role != "") ? "&roleSpecified=" + escape(role) : "&roleSpecified=" + escape(cRole);

                if (cUserEmail != "" && cUserEmail != userEmail) { // If the user enter a different email than before we create them as a new user just in case they are on a public computer
                    addNewUser(userName, phone, mobilePhone, userEmail, role, '', '');
                    return false;
                }

                $.ajax({ // Update DB with new user info
                    type: "GET",
                    url: "/webservices/FirstAMVisitorTrackingService/VisitorTrackingService.svc/UpdateVisitorInfo",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: "&visitorID=" + userId + qUserName + qPhone + qMobilePhone + "&email=" + escape(userEmail) + qRole,
                    error: function () { if (dbGenUser == false) addNewUser(userName, phone, mobilePhone, userEmail, role, '', ''); else jqueryError; }
                });
            },
            error: jqueryError
        });
    } else {
        addNewUser(userName, phone, mobilePhone, userEmail, role, '', '');
    }
}
function addNewUser(userName, phone, mobilePhone, userEmail, role, pageLocation, rating) {
    $.ajax({
        type: "GET",
        url: "/webservices/FirstAMVisitorTrackingService/VisitorTrackingService.svc/AddNewVisitor",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            createCookie("userId", result.VisitorID, 10000);
            if (userEmail != "") // create new visitor
                updateUser(result.VisitorID, userName, phone, mobilePhone, userEmail, role)
            if (rating != "") // create new feedback
                addVisitorFeedback(result.VisitorID, pageLocation, rating);
        },
        error: jqueryError
    });
}
// ******** End User Tracking Functions *********


function getPrevViewed() {
    var c = "";
    var cArray = new Array();
    var pageURL = "";
    var pageTitle = "";
    var pageDesc = "";
    var prevViewedHTML = "";

    // List Cookie Data on the Page
    var i = 0;
    while (i <= 4) {
        if (readCookie("prevViewed" + i)) {
            c = unescape(readCookie("prevViewed" + i));

            if (c.indexOf("::") != -1)
                cArray = c.split("::");
            else
                cArray = c.split(",");

            pageURL = (cArray[0].indexOf("<") != -1) ? "" : cArray[0];
            pageTitle = (cArray[1].indexOf("<") != -1) ? "" : cArray[1];
            //pageDesc = ''+cArray[2]+'';


            prevViewedHTML = '<a href="' + pageURL + '"><strong>' + pageTitle + '</strong></a>'; // <br />' + pageDesc + '</a>';
            prevViewedDivider = '<div class="hr"><img src="/assets/images/spacer.gif" /></div>';

            $("#prevViewedWrapper").html($("#prevViewedWrapper").html() + prevViewedHTML);

            if (readCookie("prevViewed" + (i + 1)))
                $("#prevViewedWrapper").html($("#prevViewedWrapper").html() + prevViewedDivider);

            $("#prevViewedBox").show();
        }
        i++;
    }
}

// Dat / Time Webservice
function getDateTime() {
    $.ajax({
        type: "GET",
        url: "/webservices/FirstAMDateTimeService/DateTimeService.svc/GetServerDateTime",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: updateDateTime,
        error: jqueryError
    });
}
function updateDateTime(result) {
    today = new Date(result);
    sTime = today.getTime(); //returns seconds since 1970
}
function dateError(request, status, error) {
    //document.getElementById("divError").innerHTML = request.responseText;
}

//Init Buttons / (disabled For IE6 or less)
function initButtons() {
    $(".btn.normal.med").bind("mouseenter mouseleave", elementHover);
    $(".btn.icoSubmit.med").bind("mouseenter mouseleave", elementSubmitHover);
    $(".btn.normal.small").bind("mouseenter mouseleave", elementSmallHover);
    $(".btn.icoSubmit.small").bind("mouseenter mouseleave", elementSmallSubmitHover);
}

//Hide / Show the Select tags when Modal Window is enabled / disabled (For IE6 or less)
function toggleSelect(action) {
    if (/MSIE (\d+\.\d+);/.test(uAgent)) { //test for MSIE x.x;
        var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion <= 6) {
            $("select").toggleClass("hide");
        }
    }
}
function toggleFly(e, el) {
    if (e.type == "mouseenter") {
        el.show();
    } else {
        if (el)
            el.hide();
    }
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

// Search Functions
var searchLink;
var qField;
function initSearch(qField, searchLink, defaultVal, btnId) { // qField is the search field ID (#_q), searchLink is the link to search page from server, defaultVal is the default text, btnID is the id of the search button
    var qFieldEl = $(qField);
    searchLink = searchLink;
    qField = qField;
    qFieldEl.bind("focus", function () {
        if (this.value == defaultVal) this.value = '';
        $(this).css("color", "#464646");
    });
    qFieldEl.bind("blur", function () {
        if (this.value == '') {
            $(this).css("color", "#959595");
            this.value = defaultVal;
        }
    });
    qFieldEl.bind("keypress", function (e) {
        var i = 0;
        var charCode = (e.which) ? e.which : window.event.keyCode;

        if (charCode == 13) {
            if (checkQ(this)) {
                window.location = searchLink + qFieldEl.val();
                return false;
            }
        } else {
            return true;
        }
    });
    $(btnId).bind("click", function () { if (checkQ($(qField))) window.location = searchLink + $(qField).val(); });
}
// Check Search Value and validate
function checkQ(q) {
    if ((q.value == "by keyword" || q.value == "Search" || q.value == "")) {
        q.value = "";
        q.focus();
        return false;
    } else {
        return true;
    }
}

function init() { // Init
    //alert($(this.parentNode + "> .off").className);
    $("#sysOrderCenter").bind("mouseenter mouseleave", function (e) { toggleFly(e, $("#sysOrderCenter .orderBoxOver")) });
    var topNavContainers = $("#header .closed"); //$D.getElementsByClassName("closed","","header");
    $(topNavContainers).bind("mouseenter mouseleave", topNavHover);
    $("#breadcrumb").bind("mouseenter mouseleave", elementHover);
    $("#utilNav").bind("mouseenter mouseleave", elementHover);

    var allStars = $("#star1,#star2,#star3,#star4,#star5");
    allStars.bind("mouseenter mouseleave", starHover);
    allStars.bind("click", setPageRating);
    checkPageRating();

    checkPromosDates();

    initModals();
    initButtons();
    if ($("#utilNav").length != 0)
        fontSizeRead();
    if ($("#sharePage").length != 0) {

        $("#sharePage").bind("mouseenter", function () { $("#shareFly").show(); toggleSelect("hide") });
        $("#shareFly").bind("mouseleave click", function () {
            $("#shareFly").hide();
            toggleSelect("show");
        });
    }

    $("#socTwitter").click(function (e) {
        e.preventDefault();
        getShortURL();
    });

    if ($("#emailPageForm").length > 0)
        initEmailThisPage();
    if ($("#contactForm").length > 0)
        initContact();
    if ($("#vcardForm").length > 0)
        initVcard();


    if (uAgent.toLowerCase().search("windows ce") > -1) // This fixes windows mobile bug where screen is stretched much too wide.
        $("body").css("width", window.screen.width);

    if (mobileBypass == "true") {
        if ($(".returnToMobileLink").length > 0) {
            $(".returnToMobileLink").click(function () { // If user chooses to return to the mobile site from the full site on a mobile device we clear the mobileBypass cookie
                createCookie("mobileBypass", "", -1);
            });
            $(".returnToMobileLink").show();
        }
    }
    if (uAgent.toLowerCase().indexOf("blackberry") > -1) {
        if ($("#mobileBypassLink").length > 0) {
            $("#mobileBypassLink").click(function (e) {
                var r = confirm('Please be aware that the full site may not perform well with some Blackberry mobile devices. Click "OK" to continue or "Cancel" to return.');
                if (r != true)
                    stopEvent(e);
                else
                    return true;
            });
        }
    }

    $("a[target='_blank']").bind("click", function () { _gaq.push(["_trackPageview", this.href]); });

    MM_preloadImages('/assets/images/arrow-black.gif', '/assets/images/ico-email-over.gif', '/assets/images/ico-print-over.gif');
}
$(document).ready(init);
