var cl = cl || {};

Event.observe( window, 'load', function(){
    // ***** jump to a spot on the page *****
    // if a query-string contains a parameter named 'jump' and an element (of any sort) contains an id
    // defined by the jump parameter, this function will jump to that element on the page.
    function jumpcheck(){
        var checkfor = parent.document.URL.toQueryParams();
        if (checkfor.jump){
            if (checkfor.jump == 'skinconsultation') { launchSkinConsultation(); }
            else if (checkfor.jump == 'foundationfinder') { launchFoundationFinder(); }
            else if (checkfor.jump == 'livechatoverlay') { launchLiveChatOverlay(); }    
            else {
                onElement(checkfor.jump, function(){
                    var element = $(checkfor.jump);
                    // alert(element.cumulativeOffset());
                    // alert('found ' + checkfor.jump);
                    Effect.ScrollTo(checkfor.jump);
                }, 2, 60)
            }
        }
    };
    jumpcheck.defer();
});

document.observe("user:updated", function(){
    //dashboard = new UserDashboard();
});
	
var dashboard = null;
document.observe('dom:loaded', function(){

    dashboard = new UserDashboard();
    //user = new User();

    if (window.attachEvent && navigator.appVersion.substr(22,3)=="6.0")
        sfHover(); // For IE6

	initRollovers();

	typeaheadsearch = new TypeAheadSearch ({
		inputElementId: 'search',
		outputContainerId: 'global-typeahead-search-box',
		positionTop: 4,
		positionLeft: -126,
		activeLink: function() { $('searchbar').addClassName('searchbar-active'); },
		deactiveLink: function() { $('searchbar').removeClassName('searchbar-active'); }
	});


    // loadAccordions();

    if ($('scroll-container')) {
        new Control.Scroller('scrollcontent', 'handle', 'track', {
            up: "button-up",
            down: "button-down",
            onScroll: function(value, scroller) {}
        });
    }

    loadLiveChatButtons();

    // My Skin Consultation
    $$('.skinConsultationButton').each(function(button){
        button.observe('click', function(event){
            var element = Event.element(event);
            launchSkinConsultation();
        });
    });

    // Foundation Finder
    $$('.foundationFinderButton').each(function(button){
        button.observe('click', function(event){
            var element = Event.element(event);
            launchFoundationFinder();
        });
    });
});

launchFoundationFinder = function(){
    templatefactory.get('/templates/foundation_finder_overlay.tmpl').evaluateCallback({
        callback: function(html){
            generic.overlay.launch({
                content: html,
                cssStyle: {width: '798px', height: '464px'}
            });
        }
    });
};

launchSkinConsultation = function(){
	var qp = parent.document.URL.toQueryParams();
	var quizlang = qp.l;
	if(quizlang){
		// happy dance
		}
	else if(window.location.href.match("espanol")){quizlang="sp";}
	else{quizlang="en";}
    templatefactory.get('/templates/skin_consultation_overlay.tmpl').evaluateCallback({
        object: {"lang": quizlang},
        callback: function(html){
            generic.overlay.launch({
                content: html,
                cssClass: "skin-consultation-overlay",
                cssStyle: {width: '776px', height: '526px', margin: '0px', padding: '0px' }
            });
            $$('.close-link').each(function(closeLink){
            	closeLink.observe('click', function(){
                	if ($('sppVideo')) {
                    	$('sppVideo').javascriptToFlash('resumeVideo');
                	}
                });
            });
        }
    });
};

launchLiveChatOverlay = function(){
    templatefactory.get('/templates/includes/content/livechat_choices_overlay.tmpl').evaluateCallback({
        callback: function(html){
            generic.overlay.launch({
                content: html,
                cssStyle: {width: '760px', height: '420px' }
            });
            $$('.close-link').each(function(closeLink){
            	closeLink.observe('click', function(){
                	if ($('sppVideo')) {
                    	$('sppVideo').javascriptToFlash('resumeVideo');
                	}
                });
            });
        }
    });
};

/*
 * Create a lighterwindow popup button out of anything
 * with the class "lwPopupButton" applied
 * e.g.:
 *        <a href="/path/to/page.tmpl" class="lwPopupButton"
 *           popupHeight="500" popupWidth="300" printButton="true"
 *           >Inner HTML</a>
 */
function createLwPopupLinks(){
    $$('.lwPopupButton').each(function(el){
		el.observe("click", function(clickEvt) {
        	clickEvt.preventDefault();
        	triggerLwPopup(el);
        });
    });
}

triggerLwPopup = function(el) {
    var h = el.readAttribute('popupHeight') || 615;
    var w = el.readAttribute('popupWidth') || 800;
    var href = el.readAttribute('href');
    var prn = el.readAttribute('printButton') || false;
   
    generic.templatefactory.get({ path: href }).evaluateCallback({
        object: {},
        callback: function(html){
            generic.overlay.launch({
                content: html,
                cssStyle: {
                    width: w+'px',
                    height: h+'px'
                }
            });
        	
        }
    });
    
    return false;
}

initRollovers = function() {
    var images = $$("img.rollover");
    images.each( function (img) {
    	
        img.addClassName("offState");

    	var onImg = img.getAttribute("activado");
    	if ( onImg ) {
    		img.onImage = new Image();
    		img.onImage.src = onImg;
    	}

    	var offImg = img.getAttribute("desactivado");
    	if ( offImg ) {
    		img.offImage = new Image();
    		img.offImage.src = offImg;
    	}
    	
        img.observe("mouseover", function(e) {
            var thisImg = e.target;
            if (thisImg.hasClassName("offState")) {
                thisImg.removeClassName("offState");
                thisImg.addClassName("onState");
            }
            if ( thisImg.onImage ) {
            	thisImg.src = thisImg.onImage.src;
            }
        });
        
        img.observe("mouseout", function(e) {
            var thisImg = e.target;
            if (thisImg.hasClassName("onState")) {
                thisImg.removeClassName("onState");
                thisImg.addClassName("offState");
            }
            if ( thisImg.offImage ) {
            	thisImg.src = thisImg.offImage.src;
            }
        });


    });
};



// Watch for dom-load and window-load to create our popup links
document.observe("dom:loaded", function(){ createLwPopupLinks(); });
//Event.observe(window, 'load', function() { createLwPopupLinks(); });
//
// For IE 6
sfHover = function(){
    try {
        var sfEls = document.getElementById("navigation").getElementsByTagName("LI");
        for (var i=0; i<sfEls.length; i++) {
            sfEls[i].onmouseover = function(){
                this.className += " sfhover";
            }
            sfEls[i].onmouseout = function(){
                var self = this;
                var hideSubmenu = function(){
                    self.className = self.className.replace(new RegExp(" sfhover\\b"), "");
                }
                var t = setTimeout(hideSubmenu, 100);
                //this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        }
    }
    catch (err) {
        console.log('err on sfHover')
    }
};

