/*
--=.._/(        CoreLogic Global Javascript Functions      )\_..=--
       */  
  

/**
 *  @Author Will Moore and friends - ISITE Design 
 */



// jquery no conflict. use $j or jQuery outside of ready function
var $j = jQuery.noConflict(); 
var startBodyClass=""; //added for presetting the body class


// jQuery document ready
jQuery(function($) {


    // modal window
    $("a.group").fancybox({
        'titlePosition': 'inside',
        'transitionIn': 'none',
        'transitionOut': 'none',
        'autoDimensions': false,
        'height': 400,
        'width': 650,
        'padding': 30,
        'scrolling': 'auto',
        'titleShow': false,
        'overlayOpacity': 0.7
    });

    $("a#image").fancybox({
        'titleShow': false,
        'overlayOpacity': 0.7
    });

    $("a[rel=example_group]").fancybox({
        'transitionIn': 'none',
        'overlayOpacity': 0.7,
        'transitionOut': 'none',
        'titlePosition': 'inside',
        'titleFormat': function(title, currentArray, currentIndex, currentOpts) {
            return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
        }
    });


    //Show premium content
    isPremium = getCookie("IsPremium");
    $general_content = $('#general_content');
    $premium_content = $('#premium_content');
    $general_content.show();
    $premium_content.hide();
    if (isPremium.indexOf("True")!=-1) {
          $general_content.hide();
          $premium_content.show();
    }


    // JS enabled
    $('html').addClass('js');

    var $body = $('body');

    // Few setups for IE6
    if (document.all) {
        //add class to drop downs and buttons. some extra verbosity to move the class of the current item up to the the ul to avoid IE6's multiple class bugginess (.blah.over)
        var IEulClass = "";
        $('#nav>li, button').hover(
        function() { $(this).addClass('over').find('ul.cols').show(); IEulClass = $(this).attr("class"); $(this).parents("#nav").addClass(IEulClass); },
        function() { $(this).removeClass('over').find('ul.cols').hide(); $(this).parents("#nav").removeClass(IEulClass); }
        );
    } // if document.all

    //pleasantNav('#nav>li');

    // page print
    if (!$body.is('.thompson')) {
        $('.page-utility ul').prepend(core.printIcon);
        $('.print-this-page a').click(function() { core.print(); });
        // rss
        var $rssLink = $("head link[type='application/rss+xml']");
        if ($rssLink.length > 0) {
            var href = $rssLink.attr("href");
            $('.page-utility ul').append("<li class=\"rss\"><a href=\"" + href + "\">RSS Feed</a></li>");
        }
    }

    // use the label as default input text and hide the label
    $('#header input, #site-search-404 input').inputSetter();

    //set correct BODY class using #pageclass div (see Product template for example)
    bodyclass = $('#pageclass').attr('class')
    $body.addClass(bodyclass)

    // prevent submitting unchanged search input
    var initialSearchTerm = $('#header #site-search input').val();
    $('#header #site-search button').click(function() {
        var currentSearchTerm = $('#header #site-search input').val();

        if (currentSearchTerm == initialSearchTerm) {
            return false;
        }
        if (document.all && $('fieldset.industry').length > 0) {
            //IE6 doesn't want to submit the search if the sidebar solutions form is on the page. Let's fake it.

            window.location = "search.aspx?q=" + currentSearchTerm;
            return false;
        }
    });



    // webtrends analytics 
    // -- for tab clicks
    $('.tabs li a[href]').mousedown(function() {
        var $this = $(this);
        var dcsuri = $this.attr("href");
        var ti = $this.text();

        if ($body.is('.page-product') && dcsuri == "#container-RequestMoreInformation")
            dcsMultiTrack('DCS.dcsuri', dcsuri, 'WT.ti', ti, 'WT.si_p', 'Form View', 'WT.si_n', 'Request More Information');
        else if ($body.is('.page-event') && dcsuri == "#container-Register")
            dcsMultiTrack('DCS.dcsuri', dcsuri, 'WT.ti', ti, 'WT.si_p', 'Form View', 'WT.si_n', 'Event Registration');
        else
            dcsMultiTrack('DCS.dcsuri', dcsuri, 'WT.ti', ti);
    });
    // -- segments
    $("#CustomerLoginContent a").click(function() {
        var segmentCookieValue = getCookie("WT.seg1");
        //if not currently Customer, set webtrends segment cookie
        if (!segmentCookieValue.match("Current Customer")) {
            if (segmentCookieValue.length > 0)
                segmentCookieValue += ",";
            segmentCookieValue += "Current Customer";
            setCookie("WT.seg1", segmentCookieValue, 999);
        }
        //call web trends tracking to set segments.
        dcsMultiTrack('DCS.dcsuri', '/Exit-Customer-Login', 'WT.ti', 'Exit Customer Login', 'WT.seg1', "Current Customer", 'WT.seg2', $(this).text());

        return true;
    });
    $(".nav-investors a, .nav-about a, .footer-links a, #secondary .nav a").click(function() {
        if ($(this).text().toLowerCase().match("investor")) {
            var segmentCookieValue = getCookie("WT.seg1");
            //if not currently Customer, set webtrends segment cookie
            if (!segmentCookieValue.match("Investor")) {
                if (segmentCookieValue.length > 0)
                    segmentCookieValue += ",";
                segmentCookieValue += "Investor";
                setCookie("WT.seg1", segmentCookieValue, 999);
            }
            dcsMultiTrack('DCS.dcsuri', '/Exit-Investor', 'WT.ti', 'Exit Investor', 'WT.seg1', "Investor");
        }
        return true;
    });

    //setup left nav
    acur = $('#secondary .nav a.current');
    par1 = acur.parent();
    par2 = par1.parent();
    par3 = par2.parent('li');
    par3.addClass('active');
    $('#secondary .nav a.current').parent().parent().parent('li').addClass('active');
    $('#secondary .nav li ul').each(function() {
        var $this = $(this);
        $this.parent('li').prepend('<span></span>').addClass('parent');

        if ($this.parent('li').is(".active")) {
            return;
        } else {
            $this.hide();
        }
    });

    //bubblers. 
    $body.click(function(event) {
        var $target = $(event.target);

        // left nav
        if ($target.is('#secondary .nav span')) {
            var $parentLI = $target.parent();
            $parentLI.find("ul").eq(0).slideToggle();

            // .active spins the arrow.
            if ($parentLI.is(".active")) {
                $parentLI.removeClass('active');
            } else if ($parentLI.find("ul").length > 0) { // don't spin the arrow if there are now child uls to display.
                $parentLI.addClass('active');
            };

            return false;
        }

        // trigger reload when filter is checked on products and solutions page
        if ($target.is('.page-products #secondary input')) {
            productFilterSubmit();
        }

        return true;
    }); // end bubblers

  
    
    // the form on products and solutions submits on change. buttons are only for agents without js
    if ($body.is('.page-products')) {
        $('#secondary .check-radio-wrap button').hide();
    }





    // var IXaaa = 1; 
    $(window).bind('hashchange', function() {
        var href = window.location.hash,
hash = href.split("#"),
    $link = $j('.tabs a[href=' + href + ']');

        //console.log($link);

        // avoid a double click
        if (!$link.parent('li').is('.active')) {
            $link.click();
        }

    });


    // for the love of  tabs
    if ($(".tabs").length > 0) {

        // on tab based form submission, .NET is setting location.hash outside of the document.ready. this tests for it and puts it into our normal bucket in the core.object.
        if (location.hash.length > 1) {
            core.hashClean = location.hash.substr(1);
        }

        // is there a hash?
        if (core.hashClean && core.hashClean.length > 0) {

            //is the hash a tab?
            if ($('.tabs a[href=#' + core.hashClean + ']').length > 0) {
                cl('here');
                var $theTab = $('.tabs a[href$=' + core.hashClean + ']'),
theTabIndex = $('.tabs a').index($theTab);
                $('.tabs').IX_tabs(theTabIndex);

                //it's a hash, but it's not a tab. Must be an 'anchor'. Let's find it and trigger the correct tab
            } else {

                if ($('#' + core.hashClean).length > 0) {

                    var $this = $('#' + core.hashClean);

                    var theTab = "#" + $this.parents('.tab').attr('id'),
theTabIndex = $('.tabwrap>div').index(theTab);

                    //trigger the correct tab
                    $('.tabs').IX_tabs(theTabIndex);
                    // move to the 'anchor'
                    IX_scrollPage($this, "slow");

                    //there's a hash,but it doesn't exist on the page. Plain tabs for you. 
                } else {
                    $('.tabs').IX_tabs();
                }

            }

            //there is no hash. default behavior please
        } else {
            $(window).trigger('hashchange');
            $('.tabs').IX_tabs();
        }


    }

    // toggle all checkbox behavior
    $(".checkbox-toggle-all").append('<li class="check-radio-wrap"><label><input class="toggle-all" type="checkbox">All of the above</a></label></li>').each(function() {
        var $cbOuter = $(this);
        $cbOuter.find("input.toggle-all").click(function() {
            var isChecked = $(this).attr('checked');
            $cbOuter.find("input:checkbox").attr('checked', isChecked);
        });
    });
    
    $.address.change(function (event) {
        // this code is used to set server side field to current hash value. Hash will reset from this field after form is submitted
        currentHash = window.location.hash;
        hashStringObject = jQuery('[id*="_txtCurrentHash"]');
        hashStringObject.val(currentHash)

    });

});   // document ready



/**
 *  application logic
 * 
 * 
 */ 


function CoreGlobal () {
this.loader = '<h2 class="loader">Loading...</h2>';
this.currentTab = 0;
this.url = window.location;
this.hash = window.location.hash;
this.hashClean = this.hash.split("#")[1];
this.logo = '<img src="/imgs/css/logo.png" alt="CoreLogic Logo"/>';
this.printIcon = '<li class="print-this-page"><a href="#" title="Print This Page">Print this page</a></li>';
this.print = function(){
if($j('#header .brand img').length <1){
$j('#header .brand').html(this.logo).css("background-image", "none");
}
window.print(); 

};


} //CoreGlobal

var core = new CoreGlobal;


function pleasantNav(nav){
var $nav = $j(nav);
var subUlCss = {'visibility': 'visibile', 'display': 'block', 'height': 'auto'};

$nav.find('ul.cols').css(subUlCss).hide();

$nav.hover(
function () {
$j(this).find('ul.cols').stop(true, true).fadeIn('fast');
},
            function () {
$j(this).find('ul.cols').stop(true, true).delay(300).fadeOut('slow');
}
);
}





/**
 * URL Builder/Redirector for Product and Solutions Filters
 * 
 */
function productFilterSubmit() {
var newParams = "";

$j('#secondary fieldset').each(function() {
var $this = $j(this),
  params = "",
hasChecked =  false,
fieldset = $this.attr("class");
fieldset = fieldset.split(" "); // relying on the name to always being the first in the class attribute.
fieldset = fieldset[0];

//there are up to three fieldsets. industry has a select.
if (fieldset == "industry") { // should probably just grab the param from the url - it wont ever change via this function. not sure which is faster.
params = $this.find(':selected').val(); 
hasChecked = true;
} else {
$this.find("input:checked").each(function() {
params = params != "" 
? params + ";" + $j(this).val() 
: $j(this).val();
//cl(fieldset[1]+'='+params);
hasChecked = true;
}); 
};

//build the new search string
if(hasChecked){
newParams = newParams != "" 
? newParams + "&" + fieldset + "=" + params 
: fieldset + "=" + params;
} 
//cl("newParams: " + newParams);
});

//just in case the url to this page changes 
var href = window.location.href;
href = href.split("?");

//redirect
window.location = href[0]+'?'+newParams; 
}





// jQuery plugins


/**
* @tabs Plugin
* 
* $('.tabs').IX_tabs();
* $('.tabs').IX_tabs(3); // click the forth tab (index starts at 0)
*/

// generic tab builder
jQuery.fn.IX_tabs = function(tab) {
    return this.each(function() {
        var $container = jQuery(this),
$tabs = jQuery("a", this),
  panes = new Array();

        $tabs.each(function() {
            var $this = jQuery(this);

            // using the href to make the collection of panes 
            var pane = $this.attr('href');

            panes.push(pane);

function hashIt(toHash) {
toHash == "" 
? window.location.hash = window.location.hash.replace( /#.*/, "") 
: window.location.hash = toHash;
return false;
}


            $this.bind("click", function() {
                //build the jq selector. cheap.
                jQuery(panes.join(",")).addClass('tabs-hide');

                //do some class switching
                $container.find('.active').removeClass('active');
                $this.parent("li").addClass("active");

//we don't want the auto hash for tab one if you've just landed on the page.
if  (pane !== panes[0])  {  hashIt(pane); } // for everything but the first, hash
else if (window.location.hash) { hashIt(pane); } // if it's the first and there's already a hash, hash on. otherwise, shh.

//show the correct pane
                jQuery(pane).removeClass('tabs-hide');



                return false;

            });
        });
        // set which tab to show
        // if .default is available, get its index and set it. else, check for a tab index passed in or set to 0
        var show = jQuery('a.default', $container).length ? $tabs.index(jQuery('a.default')) : tab || 0;

// above extended for reading hashes
/*
var urltab = window.location.hash;
var show = urltab != "" || jQuery('a.default',$container).length 
? urltab != "" 
? $tabs.index(jQuery('a[href='+urltab+']')) 
: $tabs.index(jQuery('a.default')) 
: tab || 0;

*/

        // make sure the tab we think we can show is actually there. if so, click it. else click the first tab
        $tabs.eq(show).length ? $tabs.eq(show).click() : $tabs.eq(0).click();
    });
};



/*
Input Setter - pdf, 2008 isite design
pull label and insert as field. clear with click. 

ex: $("#sitesearch input").inputSetter(1); // makes default text lowercase
$("#sitesearch input").inputSetter(); // no lowercasing

*/

jQuery.fn.inputSetter = function(lower) {
    return this.each(function() {
        var $input = jQuery(this);
        var $label = jQuery("label[for='" + $input.attr("id") + "']");
        var labeltext = lower && lower == 1 ? $label.text().toLowerCase() : $label.text();
        $label.hide();
        var inputtext = $input.val();
        if (inputtext.length == 0)
            $input.val(labeltext);
        $input.focus(function() { if (this.value == labeltext) { this.value = ""; } })
  .blur(function() { if (!this.value.length) { this.value = labeltext; } });
    });
};


function IX_scrollPage(target, speed){
speed != "" ? speed : speed = fast;
$('html, body').animate({
scrollTop: $(target).offset().top
}, speed);
}



// etc
// clean console.log

// example: cl("If you use cl() instead of console.log(), it won't break IE when you forget to take it out.");
function cl(logit) { 
if (window.console && window.console.log) { 
if(window.console.firebug) {var args = [].splice.call(arguments, 0); console.log(args.join(" ")); } 
else {console.log(logit);}
} 
} //cl()

jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
    return this;
};

// IE6 fixes
// make sure IE has the abbr and acronym tag
if (document.all) {
    document.createElement("abbr");
    document.createElement("acronym");
}
// prevent IE6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch (e) { }

function getCookie(cookieName) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(cookieName + "=");
        if (c_start != -1) {
            c_start = c_start + cookieName.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return document.cookie.substring(c_start, c_end);
        }
    }
    return "";
}

function setCookie(cookieName, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = cookieName + "=" + value + ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}
