/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Varien
 * @package     js
 * @copyright   Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/**
 * @classDescription simple Navigation with replacing old handlers
 * @param {String} id id of ul element with navigation lists
 * @param {Object} settings object with settings
 */
/*theLinkActiveParent = '';*/
var last_selected = null;
var mainNav = function() {
    var main = {		
        obj_nav :   $(arguments[0]) || $("nav"),

        settings :  {
            show_delay      :   0,
            hide_delay      :   0,
            _ie6            :   /MSIE 6.+Win/.test(navigator.userAgent),
            _ie7            :   /MSIE 7.+Win/.test(navigator.userAgent)
        },

        init :  function(obj, level) {
            obj.lists = obj.childElements();
            obj.lists.each(function(el,ind){
                main.handlNavElement(el);
                if((main.settings._ie6 || main.settings._ie7) && level){
                    main.ieFixZIndex(el, ind, obj.lists.size());
                }
            });
            if(main.settings._ie6 && !level){
                document.execCommand("BackgroundImageCache", false, true);
            }
        },
	
		    handlNavElement :   function(list) {
            if(list !== undefined){
                
                if (list.parentNode.id == "nav"){
                    list.onmouseover = function(){                    
                        main.fireNavEvent(this,true);
                    };                    
                    list.onmouseout = function(){
                        main.fireNavEvent(this,false);
                    };                    
                }else{
                    list.onclick = function(){                    
                        main.fireNavEvent(this,true,true);
                    };                    
                
                }                    

                if(list.down("ul")){
                    main.init(list.down("ul"), true);
                }
            }
        },
		
        ieFixZIndex : function(el, i, l) {
            if(el.tagName.toString().toLowerCase().indexOf("iframe") == -1){
                el.style.zIndex = l - i;                
            } else {
                el.onmouseover = "null";
                el.onmouseout = "null";
            }
        },

		fireNavEvent :  function(elm,ev,doclick) {
		 
		
			console.debug("1. antes del if");
 			if(ev){ //onmouseover                
                elm.addClassName("over");
                elm.down("a").addClassName("over");                                 
                
                if (elm.parentNode.id == 'nav') { 
                    if (elm.childElements().length > 1 ) {
                        setBgmainopacityHeight();
						// Add by Seba
						/*
                        if(document.getElementById('bgmainopacity')){
							
							document.getElementById('bgmainopacity').style.visibility='visible';
						}
						document.getElementById('bgmaintopopacity').style.visibility='visible';
						*/
						/*$$('#product-options-wrapper select option').each(function(el) {
							el.setStyle({'visibility':'hidden'})
						})
*/
						// Add by seba
						console.debug("1.1 Ingreso por el primer if");
                        elmChilds = elm.childElements(); 
                        for (i=0;i<elmChilds.length;i++)
                        {
                            elmChilds[i].removeClassName("over");
							elmChildsChilds = elmChilds[i].childElements();
							if (elmChildsChilds){
    							for(k=0;i<elmChildsChilds.length;k++){
    								elmChildsChilds[k].removeClassName("over");
    							}
							}
							if (elmChilds[i].nodeName.toLowerCase() == 'ul' ) {
                                elmChilds[i].style.height = (document.getElementById('bgmain').offsetHeight)+'px';
                                break;
                            }
                        }
                    }
                }
				
				
				
				if (elm.parentNode.parentNode.id == 'nav') { 
				console.debug("1.2 Ingreso por el segundoif");
						elm.removeClassName("over");
						elmChilds = elm.childElements(); 
                        for (i=0;i<elmChilds.length;i++)
                        {
                            elmChilds[i].removeClassName("over");
						}
						brothers = elm.parentNode.childElements();
						for (i=0;i<brothers.length;i++)
						{
							brothers[i].removeClassName("over");
							brothersChilds = brothers[i].childElements();
							for(k=0;i<brothersChilds[i].length;k++){
								brothersChilds[i].removeClassName("over");
							}
						}
				}
				
                if (elm.childElements()[1]) {
					//console.debug("-->"+elm.childElements()[1].id);
                    main.show(elm.childElements()[1]);
                }
                
                elmBrothers = elm.parentNode.childElements();
                for (i=0;i<elmBrothers.length;i++) {
                    if (elm != elmBrothers[i]) elmBrothers[i].removeClassName("activeProd");
                }
				
            }else{ //onmouseout
				//elm.addClassName("over");								
				
				console.debug("2. ELSE");
				elm.down("a").removeClassName("over");
				if (elm.parentNode.id == 'nav') {//quito fondo, y clases a si mismo, hijos y nietos
					document.getElementById('bgmainopacity').style.visibility='hidden'; 
					document.getElementById('bgmaintopopacity').style.visibility='hidden';
					// Add by seba
					elm.removeClassName("over");
					/*elmLiChilds = elm.getElementsByTagName('li');
					for (i=0;i<elmLiChilds.length;i++)
                    {                       
                        elmLiChilds[i].removeClassName("over");
						
					}*/
                }
                if (elm.childElements()[1]) {
                   main.hide(elm.childElements()[1]);
                }
            }

			//Add to fix//

             if (typeof(doclick) != "undefined" && +elm.parentNode.id!="" && elm.parentNode.parentNode.parentNode.id != "nav" ){
			console.debug("3. DoClick");	
                    
					/*if (last_selected != null){
							$$("#"+last_selected+" li").each(
							function (el){
									if (el.id != last_selected && el.id != "" ){
										el.removeClassName("over");
										el.hide(); 
									}
								}
						);
	
						
					}*/
					/*
					$$("#level0 li.level3").each(
						function (el){
								
									
									main.hide(el); 
								
							}
					);		*/			
					console.debug("--> DoClick:" + elm.id);
					last_selected = elm.id;
					
					/*if(elm.hasClassName("level2")){
						last_selected = elm.id;	
					}else{
						last_selected = null;	
					}*/
					//console.debug(elm.id)

					elmLiChilds = elm.parentNode.getElementsByTagName('li');

					for (i=0;i<elmLiChilds.length;i++)
                    {                       

                        if (elmLiChilds[i].id != elm.id && elmLiChilds[i].id != "" ){
                            elmLiChilds[i].removeClassName("over");
                            main.hide(elmLiChilds[i].childElements()[1]); 
                                                                             
                        }                                                    						
					}
					
                
		     }               
            
        },
		
		
        show : function (sub_elm) {
			console.debug("Show()");	
            if (sub_elm.hide_time_id) {
                clearTimeout(sub_elm.hide_time_id);
            }
            sub_elm.show_time_id = setTimeout(function() {
                if (!sub_elm.hasClassName("shown-sub")) {
                    sub_elm.addClassName("shown-sub");
					//console.debug("show" + sub_elm.id)
                }
            }, main.settings.show_delay);
        },

        hide : function (sub_elm) {
            console.debug("Hide()");	
            if (sub_elm.show_time_id) {
                clearTimeout(sub_elm.show_time_id);
            }
            sub_elm.hide_time_id = setTimeout(function(){
                if (sub_elm.hasClassName("shown-sub")) {
                    sub_elm.removeClassName("shown-sub");
                }
            }, main.settings.hide_delay);
            
        }

    };
    if (arguments[1]) {
        main.settings = Object.extend(main.settings, arguments[1]);
    }
    if (main.obj_nav) {
        main.init(main.obj_nav, false);
    }
};

document.observe("dom:loaded", function() {
    //run navigation without delays and with default id="#nav"
    //mainNav();

    //run navigation with delays
    mainNav("nav", {"show_delay":"0","hide_delay":"100"});
	window.setTimeout(addbespokelinks,1000);
	window.setTimeout(removebespokefrommenu,500);
	window.setTimeout(replaceHelmetURL,500);
	window.setTimeout(replaceCartThumbnail,700);
	currentURL = document.location.href;
	
	//password for /america/investors
	if(currentURL.indexOf('/america/investors') != -1){
	
		jQuery('.page').css({opacity:'0'});
	
		if(window.prompt('Enter your Password') == 'C3k5VVpp'){
			jQuery('.page').css({opacity:'1'});
		}else{
			window.location = '/';
		}
	}
	
});

var thumbnailurl = ''

function addbespokelinks(){
	currentURL = document.location.href;
	displaybespokelink = false;
	
	var urlsbespoke=['america/100-polo-helmet-argentine-style-cottontwill.html','america/100-polo-helmet-argentine-style-leather.html','america/100-polo-helmet-lock-style-cottontwill.html','america/100-polo-helmet-lock-style-leather.html','america/tech-polo-helmet-argentine-style-cottontwill.html','america/tech-polo-helmet-argentine-style-leather.html','america/tech-polo-helmet-lock-style-cottontwill.html','america/tech-polo-helmet-lock-style-leather.html','america/c6-polo-helmet-argentine-style-cottontwill.html','america/c6-polo-helmet-argentine-style-leather.html','america/c6-polo-helmet-lock-style-cottontwill.html','america/c6-polo-helmet-lock-style-leather.html'];
	
	for(nurl = 0;nurl<urlsbespoke.length;nurl++){
		urltocheck = urlsbespoke[nurl];
		if(currentURL.indexOf(urltocheck) != -1)
			displaybespokelink = true;
	}
	
	if(displaybespokelink){
		jQuery('.product-options').append('<br><a href="http://www.casablancapolo.com/bespoke"><img src="http://www.casablancapolo.com/bespokelink.gif" /></a>');
	}
	
}

function replaceHelmetURL(){
	
	currentURL = document.location.href;
	if(currentURL.indexOf('bespoke-helmet') != -1){
		partsurl=currentURL.split('/');
		partsurl=partsurl[partsurl.length-1].replace('bespoke-helmet-','');
		partsurl=partsurl.split('-');
		partsurl=partsurl[0];
		//alert(partsurl);
		if(partsurl.length){
			thumbnailurl = 'http://www.casablancapolo.com/bespokeapp/webservice/userfiles/'+partsurl+'-snapshot-side_a.jpg';
			jQuery('#actualThumbnail').attr('src',thumbnailurl).css({width:450});
		}
	}
}

function replaceCartThumbnail(){


	try{
	jQuery('.personal-quick-access .header-cart li').each(function(){

		plink = jQuery(this).find('.productname a').attr('href');
		
		if(plink.indexOf('bespoke-helmet') != -1){
			partsurl = plink.split('/');
			partsurl=partsurl[partsurl.length-1].replace('bespoke-helmet-','');
			partsurl=partsurl.split('-');
			partsurl=partsurl[0];
		
			if(partsurl.length){
				thumbnailurl = 'http://www.casablancapolo.com/bespokeapp/webservice/userfiles/'+partsurl+'-snapshot-side_a.jpg';
			}
		
			if(thumbnailurl){
				jQuery('.personal-quick-access .productimage').html('<img src="'+thumbnailurl+'" class="shoppingbag-helmet-thumbnail">');
				jQuery('.shoppingbag-helmet-thumbnail').css({width:'100px'});
			}

			jQuery('.personal-quick-access .productspc').html('Custom Helmet');
		}
	});
	}catch(e){}
	
	
	//alert(jQuery('table').html());
	try{
	jQuery('table#shopping-cart-table a').each(function(){
		//alert(jQuery(this).html());
		
		plink = jQuery(this).attr('href');
		if(plink){
			if(plink.indexOf('bespoke-helmet') == -1) return;
			
			partsurl = plink.split('/');
			partsurl=partsurl[partsurl.length-1].replace('bespoke-helmet-','');
			partsurl=partsurl.split('-');
			partsurl=partsurl[0];
			
			if(partsurl.length){
				thumbnailurl = 'http://www.casablancapolo.com/bespokeapp/webservice/userfiles/'+partsurl+'-snapshot-side_a.jpg';
			}
		
			if(thumbnailurl){ 
				jQuery(this).parents('td').find('img').attr('src',thumbnailurl).css({width:'100px'});
			}		
		}
		
	});
	}catch(e){}
	
	//window.setTimeout(replaceCartThumbnail,1500);
}

function removebespokefrommenu(){

	jQuery('.level2 a').each(function(e){
		//alert(jQuery(this).attr('href'));		
		if(jQuery(this).attr('href') && jQuery(this).attr('href').indexOf('bespoke-helmet') != -1){
			jQuery(this).parent().remove();
		}
	});
	
	
	
	
}
