/**
 * PintCaseStudyManager loads, displays and maintains a series of PintCaseStudy objects.
 */
var PintCaseStudyManager = {
	
	/**
	 * List of sites that currently have a case study.
	 * NOTE: must match the order in which they are displayed.
	 */
	sites: [
		"chargers",
		"femsa",
		"viewsonic",
		"ver",
		"usc",
		"totalgym",
		"allergan",
		"central"
	],
	
	/**
	 * AJAX callback paths for both published and non-published versions.
	 */
	ajaxPathPublished: 		'/ajax/get-case-study.htm',
	ajaxPathNonPublished: 	'/?cid=4702',
	
	/**
	 * HTML to display in the loading panel.
	 */
	loadingHTML: '<div class="loading"><span style="color:#fff;">Loading...</span></div>',
	
	/**
	 * Debug mode.
	 */
	debugMode: false,
	
	/**
	 * Holds all of the initialized PintCaseStudyGallery objects.
	 * Keeping a list of 'pointers' allows us to skip a call to getElementById everytime you need
	 * to access a PintCaseStudyGallery object.
	 */
	pcsg: {},
	
	/**
	 * Holds a list of which PintCaseStudy(ies) that have already been loaded by their name.
	 * This helps keep track so we only load each case study's gallery ONCE.
	 */
	loaded: [],
	
	/**
	 * Holds a list of which PintCaseStudy(ies) are currently being loaded in the background.
	 */
	loading: [],
	
	/**
	 * Loads a PintCaseStudyGallery for the currently active PintCaseStudy referenced by index.
	 */
	loadGallery: function(e, index) {	
		
		// Since all the divs/links start with index 1, we need to decrease it by one
		// to match with all the arrays.
		index--;
		
		// If the gallery is already loaded, just call it.
		if (PintCaseStudyManager.isGalleryLoaded(index)) {
			// Call the same createPanel() method but pass in true since the content already exists.
			PintCaseStudyManager.pcsg[PintCaseStudyManager.sites[index]].createPanel(true);
			return;
		}
		
		// If the gallery is still being loaded, we can't do anything but wait longer.
		if (PintCaseStudyManager.isGalleryLoading(index)) {
			return;
		}
		
		// First, let's indicate that this case study's gallery is being loaded.
		PintCaseStudyManager.loading.push(PintCaseStudyManager.sites[index]);
		
		// If we made it down here, we need to create the gallery and perform the lookup.
		PintCaseStudyManager.pcsg[PintCaseStudyManager.sites[index]] = new PintCaseStudyGallery();
		
		// Assign the index to the gallery object so we don't need to look it up.
		PintCaseStudyManager.pcsg[PintCaseStudyManager.sites[index]].index = index + 1;
		
		// Let's create the panel and load the content passing false indicating that we have to perform the AJAX request.
		PintCaseStudyManager.pcsg[PintCaseStudyManager.sites[index]].createPanel(false);
	},
	
	/**
	 * Determines whether or not a case study's gallery has been loaded.
	 */
	isGalleryLoaded: function(index) {
		for (var i=0;i<PintCaseStudyManager.loaded.length;i++) {
            if (PintCaseStudyManager.loaded[i] == PintCaseStudyManager.sites[index]) {
                return true;
            }
        }
        return false;
	},
	
	/**
	 * Determines whether or not a case study's gallery is currently being loaded.
	 */
	isGalleryLoading: function(index) {
		for (var i=0;i<PintCaseStudyManager.loading.length;i++) {
            if (PintCaseStudyManager.loading[i] == PintCaseStudyManager.sites[index]) {
                return true;
            }
        }
        return false;
	},
	
	/**
	 * Remove from a site from the loading que.
	 */
	removeFromLoadingQue: function(index) {
        for (var i=0;i<PintCaseStudyManager.loading.length;i++) {
            if (PintCaseStudyManager.loading[i] == PintCaseStudyManager.sites[index]) {
                // We can't use JavaScript's delete method because we'll end up with 'holes' in our array.
    			// Instead, we just do this.
    			var tempArray = [];
    			for (var j = 0; j < PintCaseStudyManager.loading.length; j++) {
    				if (PintCaseStudyManager.loading[j] != PintCaseStudyManager.sites[index]) {
    					tempArray.push(PintCaseStudyManager.sites[index]);
    				}
    			}
    			PintCaseStudyManager.loading = tempArray;
            }
        }			
	},
	
	/**
	 * Logs to console if debug mode is on.
	 */
	log: function(x) {
		if (PintCaseStudyManager.debugMode) {
			console.log(x);
		}
	}
};

/**
 * PintCaseStudy sets up the main level carousel.
 */
var PintCaseStudy = {
	
	/**
	 * init is called first to initialize the primary level carousel.
	 */
	init: function() {

		var loadCarousels = function() {
            
			var running = false;
			var currentpage = 0;
			var selectedItem = "";
			
			var carousel2 = new YAHOO.extension.Carousel("casestudy", {
				numVisible:     1,
				animationSpeed: 0.5,
				scrollInc: 		1,
				animationCompleteHandler: function(){running = false;}
				}
			);
            
            // Get the list of primary level case study navitem links and add the click-handler.
			var navlist = document.getElementById("csnav");
			var navitems = navlist.getElementsByTagName("a");
			for (var i = 0; i < navitems.length; i++) {
				var item = navitems[i];
				YAHOO.util.Event.addListener(item, "click", getPageCS(i + 1));
			}
			
			// Set the max number of navitems that are available.
			var max = navitems.length;
			
			
			function pageCS(page, forward, e) {
				if (e) {
					YAHOO.util.Event.preventDefault(e);
				}

				if (running) {
					return;
				}
                                
				if (!page) {
					page = carousel2.getFirstVisible();
					if (forward) {
						page++;
					} else {
						page--;
					}
				}	

				if (currentpage != page) {
					if (page < 1) {
						page = max;
					} else if (page > max) {
						page = 1;
					}
						
					running = true;
					carousel2.scrollTo(page);
					
					var sitesItemId = "sites-item-" + page;
                                                
					if (selectedItem != "") {

						var selectedLiObj = YAHOO.util.Dom.get(selectedItem);
                        selectedLiObj.className = selectedLiObj.className.substr(0, selectedLiObj.className.length-2);
              		   	var anim = new YAHOO.util.Motion(selectedItem, {points: {by: [0, 10]}}, 0.25);
				   		anim.animate();
				   	        
				   		//hide old items overlay if necessary
						if (YAHOO.util.Dom.getStyle(selectedItem.replace(/sites/, "overlay"), "height") == "259px") {
							PintCaseStudy.hideDetails(document.getElementById(selectedItem.replace(/sites/, "overlay")));
						}
  					}
                    
					selectedItem = sitesItemId;   
                    var selectedLiObj = YAHOO.util.Dom.get(sitesItemId);
                    selectedLiObj.className += 'on';

					anim = new YAHOO.util.Motion(sitesItemId, {points: {by: [0, -10]}}, 0.25);
					anim.animate();
				
					currentpage = page;
				}
			};
			
			function getPageCS(page) {
				return function(e) {
                                        this.blur();
					pageCS(page, null, e);
				};
			}
		
			YAHOO.util.Event.addListener(document.getElementById("leftbutton"), "click", function(e){pageCS(0, 0, e);});
			YAHOO.util.Event.addListener(document.getElementById("rightbutton"), "click", function(e){pageCS(0, 1, e);});
			
			//do initial call 
			var newpage = 1;
			var search = window.location.hash;
			
			// Which case study are we searching for to display?
			if (search.length && search.charAt(0) == '#') {
				search = search.substring(1);
			}
			
			// Find a match for the search query in the list of available sites.
			for (var i = 0; i < PintCaseStudyManager.sites.length; i++) {
				if (PintCaseStudyManager.sites[i] == search) {
					newpage = i + 1;
					break;
				}
			}
			
			pageCS(newpage);
            setTimeout(function(){YAHOO.util.Dom.setStyle('casestudy', 'visibility', 'visible');}, 250);
            //for (var i=1;i<=max;i++)
            //    YAHOO.util.Dom.setStyle('casestudy-item-' + i, 'display', 'block');

			running = false;
		};
		
		loadCarousels();
	},
	
	/**
	 * Adds the click handler to show the details of the case study.
	 * Adds the click handler to the "View Project Gallery" link.
	 */
	loadDetails: function() {

		var elements = YAHOO.util.Dom.getElementsByClassName('moreInfo', 'div'); 
		for (var i = 0; i < elements.length; i++) {
			var clickId = elements[i].id;
			var arrowId = clickId.replace(/overlay/, "arrow");
			YAHOO.util.Event.addListener(document.getElementById(clickId), "click", PintCaseStudy.toggleDetails);
			YAHOO.util.Event.addListener(document.getElementById(arrowId), "click", PintCaseStudy.toggleDetails);
		}
		
		for (var j = 1; j <= PintCaseStudyManager.sites.length; j++) {
			YAHOO.util.Event.addListener(document.getElementById("gallery-link-" + j), "click", PintCaseStudyManager.loadGallery, j);
		}
	},
	
	toggleDetails: function() {
		var overlay;
		if (this.id.indexOf("casestudy") == 0) {
			overlay = document.getElementById(this.id.replace(/casestudy/, "overlay"));
		} else {
			overlay = document.getElementById(this.id.replace(/arrow/, "overlay"));
		}
			
		if (YAHOO.util.Dom.getStyle(overlay, "height") == "259px") {
			PintCaseStudy.hideDetails(overlay);
		} else {
			PintCaseStudy.showDetails(overlay);
		}
	},

	showDetails: function(overlay) {
		var overlayId = overlay.id;
		document.getElementById(overlayId.replace(/overlay/, "arrow") ).src = themeRootDirectory + "/images/cs_btn_down.gif";
		
		var showText = function() {
			
			var animationA = new Array();
			var texts = document.getElementById(overlayId + '-a').getElementsByTagName("li");
			for (var i = 0; i < texts.length; i++) {
				animationA.push(new YAHOO.util.Anim(texts[i], {opacity: {from: 0, to: 1}}, 0.25));
			}
			
			var animationB = new Array();
			var texts = document.getElementById(overlayId + '-b').getElementsByTagName("li");
			for (var i = 0; i < texts.length; i++) {
				animationB.push(new YAHOO.util.Anim(texts[i], {opacity: {from: 0, to: 1}}, 0.25));
			}
			
			var animationC = new Array();
			var texts = document.getElementById(overlayId + '-c').getElementsByTagName("li");
			for (var i = 0; i < texts.length; i++) {
				animationC.push(new YAHOO.util.Anim(texts[i], {opacity: {from: 0, to: 1}}, 0.25));
			}
					
			animationA[animationA.length-1].onComplete.subscribe(function(){for(var i=0;i<animationB.length;i++)animationB[i].animate();});		
			animationB[animationB.length-1].onComplete.subscribe(function(){for(var i=0;i<animationC.length;i++)animationC[i].animate();});		
			for (var i = 0; i < animationA.length; i++) {
				animationA[i].animate();
			}
		};
	
		var anim = new YAHOO.util.Anim(overlayId); 
		anim.attributes.height = {from:30, to: 259}; 
		//anim.attributes.top = {from: 259, to: 0};
		anim.duration = .5; 
		anim.method = YAHOO.util.Easing.easeOut;
		anim.onComplete.subscribe(showText);
		anim.animate();
	},

	hideDetails: function(overlay) {
		var overlayId = overlay.id;
		document.getElementById(overlayId.replace(/overlay/, "arrow") ).src = themeRootDirectory + "/images/cs_btn_up.gif";
		
		var hideRegion = function() {
			var anim = new YAHOO.util.Anim(overlayId); 
			anim.attributes.height = {from:259, to: 30}; 
			//anim.attributes.top = {from: 0, to: 259};
			anim.duration = .5; 
			anim.method = YAHOO.util.Easing.easeOut;
			anim.animate();
		};
	
		var animationA = new Array();
		var texts = document.getElementById(overlayId + '-a').getElementsByTagName("li");
		for (var i = 0; i < texts.length; i++) {
			animationA.push(new YAHOO.util.Anim(texts[i], {opacity: {from: 1, to: 0}}, 0.25));
		}
		
		var animationB = new Array();
		var texts = document.getElementById(overlayId + '-b').getElementsByTagName("li");
		for (var i = 0; i < texts.length; i++) {
			animationB.push(new YAHOO.util.Anim(texts[i], {opacity: {from: 1, to: 0}}, 0.25));
		}
		
		var animationC = new Array();
		var texts = document.getElementById(overlayId + '-c').getElementsByTagName("li");
		for (var i = 0; i < texts.length; i++) {
			animationC.push(new YAHOO.util.Anim(texts[i], {opacity: {from: 1, to: 0}}, 0.25));
		}
		
		animationC[animationC.length-1].onComplete.subscribe(hideRegion);
		for (var i = 0; i < animationA.length; i++) {
			animationA[i].animate();
		}
		for (var i = 0; i < animationB.length; i++) {
			animationB[i].animate();
		}
		for (var i = 0; i < animationC.length; i++) {
			animationC[i].animate();
		}
	}
};


/**
 * PintCaseStudyGallery object for each case study being displayed.
 */
var PintCaseStudyGallery =  function() {
	
	/**
	 * What case study is this gallery for?
	 */
	this.index = null;
	
	/**
	 * Whether or not this case study is loaded.
	 */
	this.loaded = false;
	
	/**
	 * Whether or not this case study is currently being loaded.
	 */
	this.loading = false;
	
	/**
	 * Holds a reference to this gallery object's panel.
	 */
	this.panel = null;
};


/**
 * PintCaseStudyGallery object's prototype functions.
 */
PintCaseStudyGallery.prototype = {
	
	/**
	 * Creates a panel and displays the loading div while the content is being loaded.
	 */
	createPanel: function(contentAlreadyExists) {
		
		// Create the panel.
		var panel = new YAHOO.widget.Panel("gallery-loading", { 
		    width: "800px",  
		    height: "420px",
		    fixedcenter: true,  
		    close: true,  
		    modal: true,
		    zindex: 4,
		    visible: false,
		    index: this.index
			} 
		);
		
		// If the content already exists, just load it. Otherwise, we have to do the AJAX request below.
		if (contentAlreadyExists == true) {
			panel.setBody(document.getElementById('gallery-content-' + this.index));
		} else {
			panel.setBody(PintCaseStudyManager.loadingHTML);
		}
		panel.render();

                PINT.closePINTBox = function (){
                	panel.hide();
                }

                var myclose = document.createElement("div"); myclose.className="container-close"; 
                myclose.style.marginTop = '380px'; myclose.style.marginRight = '26px'; 
                myclose.onclick = PINT.closePINTBox; /* function(){ console.log('hi'); }; */
                document.getElementById('gallery-loading').appendChild(myclose);
		
		// Removes the content from the panel and puts it back into the holder div.
		var removeContentFromPanel = function() {
			document.getElementById('galleries').appendChild(document.getElementById('gallery-content-' + this.cfg.initialConfig.index));
			var yuiWrapper = document.getElementById('gallery-loading_c');
			yuiWrapper.parentNode.removeChild(yuiWrapper);
			// Add the response text to the DOM.
			var div = document.createElement('div');
				div.id = 'gallery-loading';
			document.body.appendChild(div);
			
			// Remove the gallery-loading_mask div that YUI creates with each panel
			var div = document.getElementById('gallery-loading_mask');
			div.parentNode.removeChild(div);
		};
		
		// Click handler to deactivate the panel.
		var deactivate = function() {
			panel.hide();
			//YAHOO.util.Event.removeListener(document.getElementById("gallery-loading_mask"), "click", deactivate);
			//YAHOO.util.Event.removeListener(document.getElementById("close"), "click", deactivate);
		};
		
		// Subscribe our deactivate function to the panel's hideEvent() method.
		panel.hideEvent.subscribe(removeContentFromPanel);
		
		// Activate the panel.
		panel.show();
		
		// Add a click handler to the grey'd out area of the page.
		YAHOO.util.Event.addListener(document.getElementById("gallery-loading_mask"), "click", deactivate);
                //YAHOO.util.Event.addListener(document.getElementById("gallery-loading"), "click", deactivate);
		YAHOO.util.Event.addListener(document.getElementById("close"), "click", deactivate);
		
		// Once again, if the content already exists, we don't need to continue past this point.
		if (contentAlreadyExists == true) {
			return;
		}

                var hidePanel = function(e) {
                   panel.hide();
                }
		
		/*
		 * CaseStudyAjaxObject encapsulates the transaction request and callback logic.
		 *
		 * handleSuccess() provides success case logic
		 * handleFailure() provides failure case logic
		 * processResult() displays the results of the response from both the success and failure handlers
		 * startRequest() calling this member starts the transaction request.
		 */
		var CaseStudyAjaxObject = {
		
			/* Object properties:
			 * o.tId
			 * o.status
			 * o.statusText
			 * o.getResponseHeader[ ]
			 * o.getAllResponseHeaders
			 * o.responseText
			 * o.responseXML
			 * o.argument
			 */
			handleSuccess: function(o) {
				
				// In this handler, the o.argument is equal to this.index. :-)
				
				// Get the galleries holder div.
				var galleries = document.getElementById('galleries');
				
				// Add the response text to the DOM.
				var div = document.createElement('div');
					div.id = 'gallery-content-' + o.argument;
					div.innerHTML = o.responseText;
				galleries.appendChild(div);
				
				// Create the carousel.
				PintCaseStudyManager.pcsg[PintCaseStudyManager.sites[(o.argument - 1)]].createCarousel(o.argument);
				
				// Now that the carousel is loaded, put the gallery into the panel.
				panel.setBody(div);
                                YAHOO.util.Event.on('close', 'click', hidePanel);
				//setTimeout(function(){panel.setBody(div);}, 2000);
				
				// Mark this gallery as loaded and remove it from the loading que.
				PintCaseStudyManager.loaded.push(PintCaseStudyManager.sites[(o.argument - 1)]);
				PintCaseStudyManager.removeFromLoadingQue((o.argument - 1));
			},
		
			handleFailure: function(o) {
				// Failure handler
			},
		
			startRequest: function(path, cs) {
				YAHOO.util.Connect.asyncRequest('GET', path, callback);
			}
		};
		
		/*
		 * Define the callback object for success and failure
		 * handlers as well as object scope.
		 */
		var callback = {
			success: 	CaseStudyAjaxObject.handleSuccess,
			failure: 	CaseStudyAjaxObject.handleFailure,
			scope: 		CaseStudyAjaxObject,
			argument:	this.index
		};
		
		// What case study are we getting content for?
		var cs = PintCaseStudyManager.sites[(this.index - 1)];
		
		// Determine what path to use for the callback.
		if (PINT.isPublished) {
			var path = PintCaseStudyManager.ajaxPathPublished + '?cs=' + cs;
		} else {
			var path = PintCaseStudyManager.ajaxPathNonPublished + '&cs=' + cs;
		}
		
		// Start the AJAX request.
		CaseStudyAjaxObject.startRequest(path);
	},
	
	
	/**
	 * Creates a carousel for the gallery.
	 */
	createCarousel: function(index) {
		
		var gallery_running = false;
		
		var carousel = new YAHOO.extension.Carousel("gallery" + index + "-page", {
			numVisible:        1,
			animationSpeed:    0.5,
			scrollInc: 1,
			wrap: true,
			animationCompleteHandler: function(){gallery_running = false;}
			}
		);

		var max = document.getElementById("gallery" + index + "-links-items").getElementsByTagName("li").length - 2;
				
	    var currentpage = 1;
		function pageGallery(page, forward) {
            if (gallery_running) {
                return;
            }

			if (!page) {
				page = carousel.getFirstVisible();
				if (forward) {
					page++;
				} else { 
					page--;
				}
			}	

			if (currentpage != page) {
				gallery_running = true;
				if (page < 1) {
					page = max;
				} else if (page > max) {
					page = 1;
				}
				
				var oldParentNode = document.getElementById("gallery" + index + "-links-item-" + currentpage).parentNode;
				oldParentNode.className = "";
				
				var parentNode = document.getElementById("gallery" + index + "-links-item-" + page).parentNode;
				parentNode.className = "on";
					
				carousel.scrollTo(page);
				document.getElementById("gallery" + index + "-desc-item-" + currentpage).style.display = "none";
				document.getElementById("gallery" + index + "-desc-item-" + page).style.display = "";
				currentpage = page;
			}
			return false;			
		};

		function getPageGallery(page) {
			return function() {
				pageGallery(page);
			};
		}

		YAHOO.util.Event.addListener(document.getElementById("gallery" + index + "-left"), "click", function(){pageGallery(0, 0);});
		YAHOO.util.Event.addListener(document.getElementById("gallery" + index + "-right"), "click", function(){pageGallery(0, 1);});

		for (var i = 1; i <= max; i++) {
			YAHOO.util.Event.addListener(document.getElementById("gallery" + index + "-links-item-" + i), "click", getPageGallery(i));
		}
	}
};

YAHOO.util.Event.onAvailable("containerCS", PintCaseStudy.init); 
YAHOO.util.Event.onDOMReady(PintCaseStudy.loadDetails);
