﻿/* Easy Cookie stuff start*/

EasyCookie=(function(){var EPOCH='Thu, 01-Jan-1970 00:00:01 GMT',RATIO=1000*60*60*24,KEYS=['expires','path','domain'],esc=escape,un=unescape,doc=document,me;var get_now=function(){var r=new Date();r.setTime(r.getTime());return r;}
var cookify=function(c_key,c_val){var i,key,val,r=[],opt=(arguments.length>2)?arguments[2]:{};r.push(esc(c_key)+'='+esc(c_val));for(i=0;i<KEYS.length;i++){key=KEYS[i];if(val=opt[key])
r.push(key+'='+val);}
if(opt.secure)
r.push('secure');return r.join('; ');}
var alive=function(){var k='__EC_TEST__',v=new Date();v=v.toGMTString();this.set(k,v);this.enabled=(this.remove(k)==v);return this.enabled;}
me={set:function(key,val){var opt=(arguments.length>2)?arguments[2]:{},now=get_now(),expire_at,cfg={};if(opt.expires){opt.expires*=RATIO;cfg.expires=new Date(now.getTime()+opt.expires);cfg.expires=cfg.expires.toGMTString();}
var keys=['path','domain','secure'];for(i=0;i<keys.length;i++)
if(opt[keys[i]])
cfg[keys[i]]=opt[keys[i]];var r=cookify(key,val,cfg);doc.cookie=r;return val;},has:function(key){key=esc(key);var c=doc.cookie,ofs=c.indexOf(key+'='),len=ofs+key.length+1,sub=c.substring(0,key.length);return((!ofs&&key!=sub)||ofs<0)?false:true;},get:function(key){key=esc(key);var c=doc.cookie,ofs=c.indexOf(key+'='),len=ofs+key.length+1,sub=c.substring(0,key.length),end;if((!ofs&&key!=sub)||ofs<0)
return null;end=c.indexOf(';',len);if(end<0)
end=c.length;return un(c.substring(len,end));},remove:function(k){var r=me.get(k),opt={expires:EPOCH};doc.cookie=cookify(k,'',opt);return r;},keys:function(){var c=doc.cookie,ps=c.split('; '),i,p,r=[];for(i=0;i<ps.length;i++){p=ps[i].split('=');r.push(un(p[0]));}
return r;},all:function(){var c=doc.cookie,ps=c.split('; '),i,p,r=[];for(i=0;i<ps.length;i++){p=ps[i].split('=');r.push([un(p[0]),un(p[1])]);}
return r;},version:'0.2.1',enabled:false};me.enabled=alive.call(me);return me;}());

/*Easy Cookie end*/

function submitAspForm() {
    $('#aspnetForm').submit();
}

function initCityPreferenceSelect() {
    $('#city_preference_selection').change(submitAspForm);    
}

function styleDropDowns() {
    $('select').selectbox();
}

/* init city preference select on dom ready*/
$(initCityPreferenceSelect);

/* style selects on dom ready*/
$(styleDropDowns);


/*login box stuff*/
var $sweetInsiderBox = $("#sweet_insider");
if ($sweetInsiderBox.length > 0) {
    $sweetInsiderBox.find("a.login").eq(0).click(showHola);
}

function showHola() {
    initPasswordWaterMark();
    //hide insider and show hola on callback
    $sweetInsiderBox.slideUp(1000,function(){$("#login_hola").slideDown(1000);});
}

/* city preference prompt stuff */
var $cityPrefPopup = $("#city_popup");


function toggleCityPopup(evt) {
    if ($("#city_popup:visible").length > 0) {
        $cityPrefPopup.fadeOut(500,function () {showCityPopup(evt);});
    }
    else {
        showCityPopup(evt);
    }
    return false;
}

function showCityPopup(evt) {
    
    var $tar = $(evt.target);
    
    var $sectionName = $cityPrefPopup.find(".section_name_holder");
    $sectionName.eq(0).html($tar.html());
    $sectionName.eq(1).html($tar.html());
    
    var $pickCanada = $cityPrefPopup.find("#pick_canada");
    if ($tar.hasClass("select_cityonly")) {
        $pickCanada.hide();
        $("#msg_city").hide();
        $("#msg_city_only").show();
        $("#pick_or").hide();
    }
    else {
        $pickCanada.show();
        $("#msg_city_only").hide();
        $("#msg_city").show();
        $("#pick_or").show();
        $pickCanada.click(function () {
                                        window.location = evt.target.href + "?city_pref=canada";  
                                      });
    }
    var $pickCity = $cityPrefPopup.find("#pick_city");
    $pickCity.change(function () {
                                    if ($pickCity.attr("value") !== "") {
                                        window.location = evt.target.href + "?city_pref=" + $pickCity.attr("value");
                                    }
                                 })
    var p = $tar.position();
    var topPos = Math.round( (p.top + ($tar.height() / 2)) - ($cityPrefPopup.height() / 2) );
    $cityPrefPopup.find(".close_popup").click(closeCityPopup);
    $cityPrefPopup.css({top:topPos + "px"});
    $cityPrefPopup.fadeIn(500);
    return false;
}

function closeCityPopup() {
    $cityPrefPopup.fadeOut(500);
}

function initCityPrefPopup() {
    var cityPreference = EasyCookie.get('city_preference');
    if (cityPreference !== null) {
       if (cityPreference === "canada") {
            $(".select_cityonly").click(toggleCityPopup);
       }
    }
    else {
        $(".select_cityonly").click(toggleCityPopup);
        $(".select_city").click(toggleCityPopup);
    }
}

$(initCityPrefPopup);
/* end city preference prompt stuff */

/*some stuff for fancy looking dropdowns*/
function makeRaisePopulatedFireOnce() {
             if (AjaxControlToolkit.CascadingDropDownBehavior) {
             AjaxControlToolkit.CascadingDropDownBehavior.prototype._setOptions = function(list, inInit, gettingList) {

            if (!this.get_isInitialized()) {
                return;
            }

            var e = this.get_element();
            // Remove existing contents
            this._clearItems();

            // Populate prompt text (if available) 
            var headerText;
            var headerValue = "";
            if (gettingList && this._loadingText) {
                headerText = this._loadingText;
                if ( this._selectedValue) {
                    headerValue = this._selectedValue;
                }
            } else if (!gettingList && list && (0 == list.length) && (null != this._emptyText)) {
                headerText = this._emptyText;
                if (this._emptyValue) {
                    headerValue = this._emptyValue;
                }
            } else if (this._promptText) {
                headerText = this._promptText;
                if (this._promptValue) {
                    headerValue = this._promptValue;
                }
            }
            if (headerText) {
                var optionElement = new Option(headerText, headerValue);
                e.options[e.options.length] = optionElement;
            }

            // Add each item to the DropDownList, selecting the previously selected item
            var selectedValueOption = null;
            var defaultIndex = -1;

            if (list) {
                for (i = 0 ; i < list.length ; i++) {
                    var listItemName = list[i].name;
                    var listItemValue = list[i].value;
                    
                    if (list[i].isDefaultValue) {
                        defaultIndex = i;
                        if (this._promptText) {
                            // bump the index if there's a prompt item in the list.
                            //
                            defaultIndex++;
                        }
                    }

                    var optionElement = new Option(listItemName, listItemValue);
                    if (listItemValue == this._selectedValue) {
                        selectedValueOption = optionElement;
                    }

                    e.options[e.options.length] = optionElement;
                }
                if (selectedValueOption) {
                    selectedValueOption.selected = true;
                }
            }
            
            // if we didn't match the selected value, and we found a default
            // item, select that one.
            //
            if (selectedValueOption) {
                // Call set_SelectedValue to store the text as well
                this.set_SelectedValue(e.options[e.selectedIndex].value, e.options[e.selectedIndex].text);
            } else if (!selectedValueOption && defaultIndex != -1) {
                e.options[defaultIndex].selected = true;
                this.set_SelectedValue(e.options[defaultIndex].value, e.options[defaultIndex].text);
            } else if (!inInit && !selectedValueOption && !gettingList && !this._promptText && (e.options.length > 0)) {
                // If no prompt text or default item, select the first item
                this.set_SelectedValue(e.options[0].value, e.options[0].text);
            } else if (!inInit && !selectedValueOption && !gettingList) {
                this.set_SelectedValue('', '');
            }

            if (e.childDropDown && !gettingList) {
                for(i = 0; i < e.childDropDown.length; i++) {
                    e.childDropDown[i]._onParentChange();
                }
            }
            else {
                if (list && (Sys.Browser.agent !== Sys.Browser.Safari) && (Sys.Browser.agent !== Sys.Browser.Opera)) {
                    // Fire the onchange event for the control to notify any listeners of the change
                    if (document.createEvent) {
                        var onchangeEvent = document.createEvent('HTMLEvents');
                        onchangeEvent.initEvent('change', true, false);
                        this.get_element().dispatchEvent(onchangeEvent);
                    } else if( document.createEventObject ) {
                        this.get_element().fireEvent('onchange');
                    }
                }
            }

            // Disable the control if loading/prompt text is present and an empty list was populated
            if (this._loadingText || this._promptText || this._emptyText) {
                e.disabled = !list || (0 == list.length);
            }

            //want this to just once, not sure if this has any other unanticipate consequences
            if (!gettingList) {
                this.raisePopulated(Sys.EventArgs.Empty);
            }
        };
        }

           
            
}
$(makeRaisePopulatedFireOnce);


function fancyCascade(parentId, behaveId, ddlId, clientStateId) {
    var ddlSubCatSide = $find(behaveId);
    //alert('find');
     $('#' + parentId).change(function(){
         ddlSubCatSide._onParentChange(null, true);
        
    });
    
    $('#' + ddlId).change(function(){
         var ddlVal = $(this).val();
         $('#' + clientStateId).val(ddlVal + ':::' + ddlVal);
        
    });

    ddlSubCatSide.add_populated(function(o, evtArgs)
    {
        var id = o.get_element().id;
        var i = '#' + id + '_input';

        $('#' + id + '_input_div').remove();
        $('#' + id + '_outer_div').remove();
        $('#' + id + '_inner_div').remove();
        $('#' + id + '_input').remove();
        $('#' + id + '_container').remove();
        $('#' + id + '_ddlleft').remove();
        $('#' + id).selectbox();
    });
    
    //for webkit
    //$('#' + parentId).val('');
    $('#' + parentId).change();
    
}

/*end dropdown stuff*/

/*textarea maxlength taken from PPK (quirksmode.org)*/

var W3CDOM = document.createElement && document.getElementsByTagName;



function setMaxLength() {
	if (!W3CDOM) return;
	var textareas = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<textareas.length;i++) {
		if (textareas[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.innerHTML = '<span>0</span>/'+textareas[i].getAttribute('maxlength');
			textareas[i].parentNode.insertBefore(counterClone,textareas[i].nextSibling);
			textareas[i].relatedElement = counterClone.getElementsByTagName('span')[0];
			textareas[i].onkeyup = textareas[i].onchange = checkMaxLength;
			textareas[i].onkeyup();
			textareas[i].onkeydown = imposeMaxLength;
		}
	}
}

function checkMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
//	if (currentLength > maxLength)
//		this.relatedElement.className = 'toomuch';
//	else
//		this.relatedElement.className = '';	
	this.relatedElement.firstChild.nodeValue = currentLength;
}

function imposeMaxLength(e){
    var evt = e || window.event;
    var specialKeys = [3,6,8,9,13,16,17,18,19,20,27,33,34,35,36,37,38,39,40,44,45,46];
    var specialKeyPressed = false;
    for(var i=0; i < specialKeys.length; i++) {
        if(evt.keyCode == specialKeys[i]) {
         specialKeyPressed = true;
        }
    }
    if(!specialKeyPressed) {
        return (this.value.length < this.getAttribute('maxlength'));
    } else {
        return true;
    }
}

/*comscore*/
function loadComscoreScript() {
    var cs = document.createElement('script');
    cs.type = 'text/javascript';
    cs.src = (document.location.protocol == "https:" ? "https://sb" : "http://b") + ".scorecardresearch.com/beacon.js";
    //flag to indicate whether scripts "load" has fired before  "readystatechange"
    cs.onloadDone = false;

    //function to be called after the beacon script is loaded
    function comscoreTrack() {
        COMSCORE.beacon({
            c1: 2,
            c2: 3005682,
            c3: "",
            c4: "",
            c5: "",
            c6: "",
            c15: ""
        });
    }

    cs.onload = function() {
        cs.onloadDone = true;
        comscoreTrack();
    };
    cs.onreadystatechange = function() {
        if (('loaded' === cs.readyState || 'complete' === cs.readyState) && !cs.onloadDone) {
            cs.onloadDone = true;
            comscoreTrack();
        }
    };
    
    document.getElementById('comscore').appendChild(cs);
}
$(loadComscoreScript);

function loadTracer() {
  var s=document.createElement('script');
  s.setAttribute('src','http://tcr.tynt.com/javascripts/Tracer.js?user=b7TPKqi3Sr3QJUacn9QLxW&s=30');
  document.getElementById('comscore').appendChild(s);
}
$(loadTracer);

$(function(){$('body').trigger('loadAds');});
 
 function iResize(fid,h,sz) {
	var iFrame1 = document.getElementById(fid);

    switch(sz) {
        case '728x90':
            h = 90;
            break;
         case '300x250':
            h = 250;
            break;
         case '160x600':
            h = 600;
            break;
         case '300x250,300x600':
            if (Math.abs(h - 250) > Math.abs(h - 600)) {
                h = 600;
            } else {
                h = 250;
            }
            break;
    }
    
	iFrame1.style.height = h + 'px';

 }

//notify script manager that script has been loaded
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); 



