document.observe("dom:loaded", function(){
    
    $$('body')[0].addClassName(pageVars.pageName.toLowerCase()); // Add Iexterior360 | Interior class to the body
    
    /* Search for trim in the URL*/
    var currentTrim = (window.location.search.indexOf('trim=') !== -1) ? window.location.search.split('trim=')[1].split('&')[0] : '';    
    var currentView = trimImagePath = '';    
    var counter = currentColor = 0, viewFullImgName = 1;
    var imgContainer = $('flashcontent');
    
    // Returns the images path    
    var createImgPath = function(){                        
        if (pageVars.pageName === 'Exterior360'){                 
            return (currentTrim === '' || isNaN(currentColor)) ? false : trimCodes[currentTrim].imagePath + colorCodes[currentColor].folder + '/###.jpg';
        }
        if (pageVars.pageName === 'Interior'){
            return (currentTrim === '' || isNaN(currentColor) || isNaN(viewFullImgName) || currentView === '') ? false : trimCodes[currentTrim].imagePath + currentView + viewFullImgName + '.' + trimCodes[currentTrim].imageExtension;
        }
    };  
    
    /** create TRIMS list **/    
    var trimsContainer = $$('#content_head_tools .trims')[0];   
    
    var createtrimsList = function(){
        var trimList = (TMSSite.lang === 'en') ? '<p>Choose a model:</p><ul>' : '<p>Elige un modelo:</p><ul>';        
           
        for(var trim in trimCodes){                
            var elState = '';        
            // Set default trim
            if(currentTrim === '' && counter === 0){             
                currentTrim = trim;
                elState = 'active';           
            }else if(currentTrim === trim){
                elState = 'active';
            }
            trimList += '<li><a href="#" rel="'+trim+'" class="'+elState+'">'+trimCodes[trim].label+'</a></li>';
            counter++;        
        }
        
        trimList += '</ul>';
        
        trimsContainer.innerHTML = trimList; // Add the list to the HTML                   
    };

    /** create COLOR list **/            
    var colorContainer = $$('#content_head_tools .colors')[0];
    
    var createColorList = function(colors){        
        var colorList = (TMSSite.lang === 'en') 
			? (pageVars.pageName === 'Exterior360') ? '<p>Choose an exterior color:</p><ul>' : '<p>Choose an interior color:</p><ul>'
			: (pageVars.pageName === 'Exterior360') ? '<p>Elige un color exterior:</p><ul>' : '<p>Elige un color interior:</p><ul>' ;
		
		var fullViewName = 1;
        
        var validColor = false;
                
        for(var counter = 0; counter < colors.length; counter++){

            if(typeof colorCodes[colors[counter]] === 'undefined') //check if array is empty            
                break;
            
            colors.each( function(value) {  
                if(value === currentColor){ validColor = true; } // Check if current color is in the new colors array
            });
            
            currentColor = (!validColor) ? colors[0] : currentColor; // If current color isn't in the available colors arrays then use the first one of that array 

            var elState = (currentColor == colors[counter]) ? 'active' : '' ; // Set active state to the proper color                    
            
            if(pageVars.pageName === 'Exterior360'){                            
                colorList += '<li><a href="#" rel="'+colors[counter]+'" class="'+elState+'" style="background-color:#'+colorCodes[colors[counter]].hexCode.split('0x')[1]+';"><span>'+colorCodes[colors[counter]].label+'</span><div class="mask"></div></a></li>';
            }
            
            if(pageVars.pageName === 'Interior'){
                fullViewName = colorCodes[colors[counter]].texture.split('/swatch_textures/')[1].split('.')[0];                
                colorList += '<li><a href="#" rel="'+ colors[counter] +'-'+ fullViewName +'" class="'+elState+'" style="background:transparent url(\''+colorCodes[colors[counter]].texture+'\') no-repeat 0 0;"><span>'+colorCodes[colors[counter]].label+'</span></a></li>';
            }
        }
        
        colorList += '</ul>';        
    
        colorContainer.innerHTML =  colorList;
        
        // Set default interior view full path
        viewFullImgName = $$('.colors li a')[0].rel.split('-')[1];
        // Validate texture name is a number, otherwise ose the color id
        viewFullImgName = (isNaN(viewFullImgName)) ? (currentColor + 1) : viewFullImgName; 
    };

    // Create INTERIOR VIEWS
    
    var viewContainer = $$('#content_head_tools .views')[0];     
        
    var createViews = function(){        
                
        var viewsList = (TMSSite.lang === 'en') ? '<p>Choose a view:</p><ul>' : '<p>Elige una vista:</p><ul>' ;
        var counter = 0;
        
        for(var view in trimCodes[currentTrim].angles){                
            var elState = '';                    
            
            if(currentView === '' && counter === 0){ // Set default view             
                currentView = view;
                elState = 'active';           
            }else if(currentView === view){ // Or keep the current view
                elState = 'active';
            }
            
            viewsList += '<li><a href="#" rel="'+view+'" class="'+elState+'"><img src="'+trimCodes[currentTrim].angles[view]+'" alt="'+view+'" /></a></li>';
            counter++;        
        }        
        
        viewsList += '</ul>';
        
        viewContainer.innerHTML = viewsList;
    };
        
    var viewImg = new Image();
      $(viewImg).observe('load',function(e){            
            imgContainer.innerHTML = ''; // Clean the container
            imgContainer.insert(viewImg);
        });
    
    var loadView = function(viewPath){           
        imgContainer.innerHTML = '<img src="/img/search/ajax-loader.gif" class="loader" />';
        viewImg.alt = colorCodes[currentColor].label;
        viewImg.src = viewPath;                        
    };

    //Events
               
    // LOAD DEFAULT TRIMS in  EXT 360 & INT                   
    createtrimsList();    
    // LOAD DEFAULT COLORS in  EXT 360 & INT
    if(typeof trimCodes[currentTrim] !== 'undefined')
        createColorList(trimCodes[currentTrim].colors); // Add the list to the HTML
    // LOAD DEFAULT TRIM CAROUSEL EXT 360
    if(pageVars.pageName === 'Exterior360' && createImgPath()){           
        threeSixty.init(createImgPath()); // Load the default trim carousel
    }                
    //LOAD DEFAULT INT VIEW LIST ON LOAD
    if(typeof trimCodes[currentTrim].angles !== 'undefined')
        createViews(); // Fill the view list only for Int 360       
    //LOAD DEFAULT INT VIEW IMAGE ON LOAD            
    if(pageVars.pageName === 'Interior' && createImgPath()){        
        loadView(createImgPath()); // Load the default view image        
    }
    
    // ON CLICK
        
    // Trims List
    var trims = $$('.trims li a');              
    
    var cleanActiveTrims = function(){
        trims.each(function(trim){  
            if (trim.hasClassName('active')){                
                trim.removeClassName('active');
            }
        });        
    };
    
    trims.each(function(trim){                
        trim.observe('click',function(e){
            e.preventDefault();
            // Check for the target click its already selected
            if(currentTrim === $(this).rel) { return; }            
            // Clear any active button before
            cleanActiveTrims(); 
            // Add the active state event on click
            $(this).addClassName('active'); 
            // Set current trim
            currentTrim = $(this).rel;
            // Reload color list for this trim
            createColorList(trimCodes[currentTrim].colors); // Add the list to the HTML
            //Load new images for Ext 360
            if(pageVars.pageName === 'Exterior360' && createImgPath()){                
                threeSixty.init(createImgPath());        
                
        		// start omniture            
    			/*
TMSSite.analytics.set({
    				pageName: TMSSite.i18n[TMSSite.lang].pageName +':'+ pageVars.vehicleDisplayName + ':Photos & Colors:360 Views:Exterior:' + trimCodes[currentTrim].label,
    				properties: {
                        "2"  :	pageVars.modelYear,                    
                        "10" :	TMSSite.i18n[TMSSite.lang].pageName + ":Photos & Colors",
                        "11" :	TMSSite.i18n[TMSSite.lang].pageName + ":" + pageVars.vehicleDisplayName + ":Photos & Colors",
                        "14" :	TMSSite.i18n[TMSSite.lang].pageName + ":" + pageVars.vehicleDisplayName + ":360 Views:Exterior:" + colorCodes[currentColor].label,
                        "32" : "Middle"
    				}
    			});
                
                TMSSite.analytics.sendPageView();
*/
        		// end omniture                        
                
                    
            }
            //Load new colors for Int 360
            if(pageVars.pageName === 'Interior' && typeof trimCodes[currentTrim].angles !== 'undefined')
                createViews(); // Fill the view list only for Int 360
                                       
            //Load new view for Int 360
            if(pageVars.pageName === 'Interior' && createImgPath()){
                loadView(createImgPath());
                
        		// start omniture            
/*
    			TMSSite.analytics.set({
    				pageName: TMSSite.i18n[TMSSite.lang].pageName +':'+ pageVars.vehicleDisplayName + ':Photos & Colors:360 Views:' + trimCodes[currentTrim].label,
    				properties: {
                        "2"  :	pageVars.modelYear,                    
                        "10" :	TMSSite.i18n[TMSSite.lang].pageName + ":Photos & Colors",
                        "11" :	TMSSite.i18n[TMSSite.lang].pageName + ":" + pageVars.vehicleDisplayName + ":Photos & Colors",
                        "14" :	TMSSite.i18n[TMSSite.lang].pageName + ":" + pageVars.vehicleDisplayName + ":360 Views:" + colorCodes[currentColor].label,
                        "32" : "Middle"
    				}
    			});
        
                TMSSite.analytics.sendPageView();
*/
        		// end omniture            
                
            }                

        });        
    });

    //Colors List
    var cleanActiveColors = function(){
        $$('.colors li a').each(function(color){  
            if (color.hasClassName('active')){                
                color.removeClassName('active');
            }            
        });        
    };
    
    // Color change On click event using event delegation       
    colorContainer.observe('click',function(e){
        e.preventDefault();
        //IE doesn't pass in the event object
        e = e || window.event;        
        //IE uses srcElement as the target
        var target = e.target || e.srcElement;                            
        // bypass the mask over the A element in Ext 360
        if(target.tagName === 'DIV' && $(target).hasClassName('mask')){
            target = $(target).up();
        }        
        // Check for the target click to the mask or link not other element or if its already selected
        if(target.tagName !== 'A' || parseInt($(target).rel.split('-')[0]) === currentColor){ return; }
        // Clear any active button before
        cleanActiveColors(); 
        // Add the active state event on click
        $(target).addClassName('active'); 
        // Set new global trim
        currentColor = (pageVars.pageName === 'Exterior360') ? parseInt($(target).rel) : parseInt($(target).rel.split('-')[0]);
        // Get new view name
        viewFullImgName = (pageVars.pageName === 'Interior') ? parseInt($(target).rel.split('-')[1]) : 1;
        // Validate texture name is a number, otherwise ose the color id
        viewFullImgName = (isNaN(viewFullImgName)) ? (currentColor + 1) : viewFullImgName;
        //Load new images for Ext 360
        if(pageVars.pageName === 'Exterior360' && createImgPath()){            
            threeSixty.init(createImgPath());            

    		// start omniture            
/*
    		var oEvent = {
    			properties:{
    							'14':TMSSite.i18n[TMSSite.lang].pageName + ':' + pageVars.vehicleDisplayName + ':360 Views:Exterior:' + colorCodes[currentColor].label
    						},
    			linkTrackVars:	'prop14',
    			linkTrackType: 'o',
    			linkTrackName: ((TMSSite.i18n[TMSSite.lang].pageName == "GM") ? "tcom" : "esp") + '_photos_360views_exterior_' + pageVars.modelCode
    		};
    		TMSSite.analytics.sendTrackingLink(oEvent); 
*/   		
    		// end omniture            

        }
        //Load new colors for Int 360
        if(pageVars.pageName === 'Interior' && typeof trimCodes[currentTrim].angles !== 'undefined')
            createViews(); // Fill the view list only for Int 360                       
            
        //Load new view for Int 360
        if(pageVars.pageName === 'Interior' && createImgPath()){
            loadView(createImgPath());
            
    		// start omniture            
/*
    		var oEvent = {
    			properties:{
    							'14':TMSSite.i18n[TMSSite.lang].pageName + ':' + pageVars.vehicleDisplayName + ':Photos & Colors:360 Views:Interior:' + trimCodes[currentTrim].label + ":" + colorCodes[currentColor].label + ":Side View"
    						},
    			linkTrackVars:	'prop14',
    			linkTrackType: 'o',
    			linkTrackName: ((TMSSite.i18n[TMSSite.lang].pageName == "GM") ? "tcom" : "esp") + '_photos_360views_interior_' + pageVars.modelCode
    		};
    		TMSSite.analytics.sendTrackingLink(oEvent); 
*/   		
    		// end omniture            
            
        }                
                     
    });
    
    var delayColorFlag = false; //flag used for flickering problem on IE.  flag with setTimeout will check to see if mouse is over another color before adding active class
    
    // Color Label show/hide On mouseover event using event delegation    
    colorContainer.observe('mouseover',function(e){
        e.preventDefault();
        //IE doesn't pass in the event object
        e = e || window.event;        
        //IE uses srcElement as the target
        var target = e.target || e.srcElement;                                    
        // bypass the mask over the A element in Ext 360 or not Int 360
        if(target.tagName === 'A' || target.tagName === 'DIV'){
            var activeColor = $$('.colors li a.active')[0];            
            
            //console.log(activeColor.rel) || alert(activeColor.rel);
            
            if(activeColor){
                activeColor.removeClassName('active');
            }
        } 
        
        delayColorFlag = true;       
    });   
    
    // Color Label show/hide mouseout event using event delegation
    colorContainer.observe('mouseout',function(e){  
        e.preventDefault();
        //IE doesn't pass in the event object
        e = e || window.event;        
        //IE uses srcElement as the target
        var target = e.target || e.srcElement;     
        
        if(target.tagName === 'A' || target.tagName === 'DIV'){        
            
            var activeColor = $$('.colors li a[rel|="'+currentColor+'"]')[0];
            
            /** Looks like Prototype uses the Browser CSS engine and IE doesn't recognize "rel|=" and dont use any alternative so use a workaround **/
            if(Prototype.Browser.IE){
                var activeColorIE = $$('.colors li a');
                activeColorIE.each(function(lnk){
                    if(lnk.rel.split("-")[0] == currentColor){
                        activeColor = lnk;
                    }
                });
            }      
            
            
            function resetActiveColor() {
            	if (delayColorFlag == false) {
            		activeColor.addClassName('active');
            	}
            }
            setTimeout(resetActiveColor,500); //setTimeout used with flag to resolve flickering issue for split second adding active class
            delayColorFlag = false; 
/*
            if (activeColor){
                activeColor.addClassName('active');
            } 
*/               
        }
    });        
    
    // Views List only if in Interior page to save ms
    if(pageVars.pageName === 'Interior' && typeof trimCodes[currentTrim].angles !== 'undefined'){                          
        
        var cleanActiveViews = function(){
            $$('.views li a').each(function(view){  
                if (view.hasClassName('active')){                
                    view.removeClassName('active');
                }
            });        
        };
        
        // View change Onclick event using event delegation
        viewContainer.observe('click', function(e){
            e.preventDefault();
            //IE doesn't pass in the event object
            e = e || window.event;        
            //IE uses srcElement as the target
            var target = e.target || e.srcElement;                    
            // move the event from IMG tag to the parent A
            if(target.tagName === 'IMG'){
                target = $(target).up(); // GET the A tag
            }                    
            // Check for the target click the link not other element or if its already selected
            if(target.tagName !== 'A' || currentView === $(target).rel){ return; }
            // Clear any active button before
            cleanActiveViews(); 
            // Add the active state event on click
            $(target).addClassName('active'); 
            // Set nue global trim
            currentView = $(target).rel;                                
            //LOAD INT VIEW
            if(createImgPath()){
                loadView(createImgPath());
            }                
        });        
    }

    /* OMNITURE */
    
    var market = TMSSite.i18n[TMSSite.lang].pageName;
    
    if (pageVars.pageName === 'Exterior360'){                 
    
    
/*
			TMSSite.analytics.set({
				pageName: TMSSite.i18n[TMSSite.lang].pageName +':'+ pageVars.vehicleDisplayName + ':Photos & Colors:360 Views:Exterior:' + pageVars.vehicleDisplayName,
				properties: {
                    "2"  :	pageVars.modelYear,                    
                    "10" :	TMSSite.i18n[TMSSite.lang].pageName + ":Photos & Colors",
                    "11" :	TMSSite.i18n[TMSSite.lang].pageName + ":" + pageVars.vehicleDisplayName + ":Photos & Colors",
                    "14" :	TMSSite.i18n[TMSSite.lang].pageName + ":" + pageVars.vehicleDisplayName + ":360 Views:Exterior:" + colorCodes[currentColor].label,
                    "32" : "Middle"
				}
			});
*/
			        
    }
    
    if (pageVars.pageName === 'Interior'){
        
/*
			TMSSite.analytics.set({
				pageName: TMSSite.i18n[TMSSite.lang].pageName +':'+ pageVars.vehicleDisplayName + ':Photos & Colors:360 Views:' + pageVars.vehicleDisplayName,
				properties: {
                    "2"  :	pageVars.modelYear,                    
                    "10" :	TMSSite.i18n[TMSSite.lang].pageName + ":Photos & Colors",
                    "11" :	TMSSite.i18n[TMSSite.lang].pageName + ":" + pageVars.vehicleDisplayName + ":Photos & Colors",
                    "14" :	TMSSite.i18n[TMSSite.lang].pageName + ":" + pageVars.vehicleDisplayName + ":360 Views:" + colorCodes[currentColor].label,
                    "32" : "Middle"
				}
			});
*/
        
    }    
    
    /* TMSSite.analytics.sendPageView(); */
    

});            

/** 360 Class for the carousel event **/
threeSixty = {
    init: function(trimImagePath) {   
        $('flashcontent').innerHTML = ''; // Clean the container before insert new carousel
        var currentPos = (this._vr) ? this._vr.getCurrentPos() : [11,0]; // Get current position of the car of set default        
        this._vr = new AC.VR('flashcontent', trimImagePath, 12, {                        
            invert: false,
            introSpins : 0,
            initialPos : currentPos,
            stopFrames: [1,5,7,10]
        });                    
    },
    didShow: function() { this.init(); },
    willHide: function() { recycleObjectValueForKey(this, "_vr"); },
    shouldCache: function() { return false; }
}
