/*
	panels parameters:
	bgimage: the background image
	thumbimage: the background image
	weight: where this panel sits as far as priority (5 will have a better chance of being chosen over 3 and 0 is off)
	timeout: time in seconds the panel will show (otherwise will show default)
	linkOffset: the position of the first link [x,y]
	linkList: an array of links [{text: "Go Here",uri: "http://www.care2.com"}]
	linkColor: the link color in hex (without the hashmark). defaults to "000"
	oneClick: removes the list of links and makes the entire panel one big link (link url defined here)
	htmlOverride: removes the links list items and puts this HTML in the spotlight
	spotlightType: linkList, oneClick, or htmlOverride
*/

CARE2.spotlight = function(id, panels, allPanels) {
	var obj = {}
	var _self = this;

	obj.panelContainer = this.isIdOrHandler(id);
	obj.timeout = 10;
	obj.currentState = "paused";
	obj.panels = panels;
	obj.animating = false;
	obj.controlIndex = 0;
	obj.formerPanel = 0;
	obj.controlOffset = 0;
	obj.numControls = 4;
	obj.allPanels = allPanels || false;

	obj.preloadImgs = function(){
		for(var l,i=0;l=obj.panels[i];i++){
			var im1 = new Image();
			im1.src = l.bgimage;
			if(l.thumbimage){
				var im2 = new Image();
				im2.src = l.thumbimage;
			}
		}
	}

	obj.randomize = function(){
		var newPanels = [];
	    var temp_keys = {first:[],last:[]};
	    var temp_order = {first:[],last:[]};
	    for(var i=0;i<obj.panels.length;i++){
	        var panel_inserted = false;
			if((obj.panels[i].weight!=0&&(obj.panels[i].userType!="new"||(obj.panels[i].userType=="new"&&!getCookie('carecards_user')))) || obj.allPanels ){
				var weight = obj.panels[i].weight;
				var k=(obj.panels[i].userType=="new" && !obj.allPanels)?"first":"last";
				if(temp_keys[k].length>0){
				    for(var j=0;j<temp_order[k].length;j++){
				        if(weight<temp_order[k][j]) {
    			            temp_keys[k].splice(j,0,i);
    			            temp_order[k].splice(j,0,weight);
    			            panel_inserted = true;
        		            break;
        		        }
				    }
				}
				if(!panel_inserted){
    				temp_keys[k].push(i);
    				temp_order[k].push(weight);
    			}
			}
        }

        temp_keys=temp_keys.first.concat(temp_keys.last);
        for(var i=0;i<temp_keys.length;i++) newPanels.push(obj.panels[temp_keys[i]]);
        obj.panels = newPanels;
	}
	
	obj.clickPanel = function(id)
	{
	   obj.thumbAction = "";
	   obj.formerPanel = obj.controlIndex;
	   obj.controlIndex = id;
	   obj.createControls(obj.controlIndex);
	}

	obj.createControls = function(id){
		if(!obj.controls){
			id=obj.showControl=0;
			var controls = _self.buildElement('div',{className:"controlPanel"});

			obj.controls = _self.buildElement('ul');
			obj.prevButton = _self.buildElement('li',{className:"prev",onclick: function(){
				if(!obj.animating){
					obj.animating=this.className;
					obj.thumbAction='prev';
					obj.formerPanel = obj.controlIndex;
					obj.controlIndex--;
					obj.createControls(obj.controlIndex);
				}
			}});
			obj.nextButton = _self.buildElement('li',{className:"next",onclick: function(){
				if(!obj.animating){
					obj.animating=this.className;
					obj.thumbAction='next';
					obj.formerPanel = obj.controlIndex;
					obj.controlIndex++;
					obj.createControls(obj.controlIndex);
				}
			}});
			obj.controls.appendChild(obj.prevButton);
			for(var l,i=0;l=obj.panels[i]&&i<obj.numControls;i++){
				var actv = (i==0) ? " active" : "";
				obj.controls.appendChild(_self.
				buildElement('li',{className:'thumb'+actv,style:{cssText:'background-image: url('+obj.panels[i].thumbimage+')'},onclick:function(x){return function(){
					obj.clickPanel(x);
				}}(i)}));

				if(obj.panels.length < obj.numControls)
				{
				    obj.numControls = obj.panels.length;
				}
			}
			obj.controls.appendChild(obj.nextButton);
			obj.pauseButton = _self.buildElement('li',{className:"pause"});
			obj.controls.appendChild(obj.pauseButton);

			controls.appendChild(obj.controls);
			obj.panelContainer.appendChild(controls);
			obj.animating=false;
		}else if(id||id==0){

            if(obj.thumbAction == ""){
                //User clicked a spotlight panel thumbnail
			    //Offset id + 1 because the arrow is the first index in the li array
			    var li = obj.controls.getElementsByTagName('li');
			    _self.removeClassName(li[obj.formerPanel+1], 'active');
			    
			    //We don't want to select one of the arrows
			    if(id+1 <= obj.numControls)
			    {
			         _self.addClassName(li[id+1], 'active');
			    }
				
			}
			else if((id < obj.numControls && obj.thumbAction=="next") || (id >= 0 && obj.thumbAction=="prev")){
			    //selecting the previous or next thumbnail without needing to scroll the elements
				var li = obj.controls.getElementsByTagName('li');
				_self.removeClassName(li[obj.formerPanel+1], 'active');
				_self.addClassName(li[id+1], 'active');
			}
			else if(obj.panels.length <= obj.numControls)
			{
			    //We're at a boundary, but we don't have enough panels to necessitate the
			    //need to scroll the thumbnails, just loop back around
			    var li = obj.controls.getElementsByTagName('li');
			    if(obj.formerPanel == 0 && obj.thumbAction == "prev")
			    {
			        _self.removeClassName(li[0+1], 'active');//Remove active class on first panel (2nd <li> index, since the arrow is the first)
				    _self.addClassName(li[obj.panels.length], 'active');
				    id = obj.panels.length-1;
				    obj.formerPanel = obj.controlIndex = id;
			    }
			    else if(obj.formerPanel == obj.numControls-1 && obj.thumbAction == "next")
			    {
			        _self.removeClassName(li[obj.formerPanel+1], 'active');
				    _self.addClassName(li[0+1], 'active'); //Add active class on first panel (2nd <li> index, since the arrow is the first)
				    id = 0;
				    obj.formerPanel = obj.controlIndex = id;
			    }
			}
			else{
			    //We need to scroll the panel controls so that the user can see the hidden ones
			    var panel;
			    if(obj.thumbAction == 'next')
			    {
			        for(var i=0; i < 3; i++)
			        {
			            panel = obj.panels.shift();
			            obj.panels.push(panel);
			        }
			    }
			    else
			    {
			        for(var i=0; i < 3; i++)
			        {
			            panel = obj.panels.pop();
			            obj.panels.unshift(panel);
			        }
			    }

				var li = obj.controls.getElementsByTagName('li');
				var panelIndex=0;
				//What's panel is going to be selected after the scroll?
				var newPanel = obj.thumbAction == "next" ? 1 : 2;

				for(var l,i=0;l=li[i];i++){
					if(l.className.indexOf('thumb') > -1){

					    var actv = "";
					    if(panelIndex == newPanel)
					    {
					        actv = " active";
					        id = panelIndex;
					        obj.controlIndex = panelIndex;
					    }

					    var el = _self.buildElement('li',{className:'thumb'+actv,style:{cssText:'background-image: url('+obj.panels[panelIndex].thumbimage+')'},onclick:function(x){return function(){
							obj.thumbAction = "";
							obj.formerPanel = obj.controlIndex;
						    obj.controlIndex = x;
							obj.createControls(obj.controlIndex);
						}}(panelIndex)});

						obj.controls.replaceChild(el, l);
						panelIndex++;
					}
				}
			}
		}
		obj.activatePanel(id);
	}

	obj.activatePanel = function(id){
		clearTimeout(obj.intvl);
		var timeout = obj.panels[id].timeout||obj.timeout;

		obj.newPanel = _self.buildElement('div',{className:"main"});

		obj.newPanel.style.cssText = "background: transparent url("+obj.panels[id].bgimage+") no-repeat scroll 0 0";

		if(obj.panels[id].spotlightType=="htmlOverride"){
			obj.newPanel.innerHTML = obj.panels[id].htmlOverride;
		}else if (obj.panels[id].spotlightType=="oneClick") {
			obj.newPanel.appendChild(_self.buildElement('a',{href:obj.panels[id].oneClick,className:"oneClick"}));
		}else{
			obj.newPanel.appendChild(_self.buildElement('ul',{className:"linkList"}));

			for(var l,i=0;l=obj.panels[id].linkList[i];i++) {
				var li = _self.buildElement('li');
				var a = _self.buildElement('a',{href:l.uri,innerHTML:l.text});
				if(obj.panels[id].linkColor) {
					var color = obj.panels[id].linkColor.replace("#","");
					if((/[0-9a-f]{3,6}$/i).test(color)){
						li.style.color = "#"+color;
						a.style.color = "#"+color;
					}
				}
				li.appendChild(a);
				obj.newPanel.getElementsByTagName('ul')[0].appendChild(li);
			}

			if(obj.panels[id].linkOffset['0'])obj.panels[id].linkOffset=[obj.panels[id].linkOffset['0'],obj.panels[id].linkOffset['1']]

			obj.newPanel.getElementsByTagName('ul')[0].style.cssText = "margin-left:"+obj.panels[id].linkOffset[0]+"px;margin-top:"+obj.panels[id].linkOffset[1]+"px";
		}

		obj.newPanel.onmouseover = function(){
			obj.pauseButton.style.visibility = "visible";
			clearTimeout(obj.intvl);
		}

		obj.newPanel.onmouseout = function(){
			obj.pauseButton.style.visibility = "hidden";
			obj.intvl = setTimeout(obj.nextButton.onclick,obj.timeout*1000);
		}

		if(obj.spotlightContainer.firstChild) {
			var tmpChild = obj.spotlightContainer.firstChild;
			tmpChild.onmouseover = null;
			tmpChild.style.zIndex = 1;
			obj.newPanel.style.zIndex = 0;
			obj.spotlightContainer.insertBefore(obj.newPanel, tmpChild);
			var fadeOut = new YAHOO.util.Anim(tmpChild, { opacity: { to: 0 } }, 0.5);
			fadeOut.onComplete.subscribe(function(){
				obj.animating=false;
				obj.spotlightContainer.removeChild(tmpChild);
			});
			fadeOut.animate();
		}else{
			obj.spotlightContainer.appendChild(obj.newPanel);
		}

		obj.intvl = setTimeout(obj.nextButton.onclick,obj.timeout*1000)
	}
	
	obj.previewPanel = function(id)
	{
	   obj.clickPanel(id);
	   clearTimeout(obj.intvl);
	}

	obj.init = function() {
		obj.panelContainer.appendChild(obj.spotlightContainer=CARE2.buildElement('div',{className:'spotlight_container'}));
		obj.randomize();
		obj.createControls(obj.controlIndex);

		_self.addListener(window,'load',obj.preloadImgs);
	}

	obj.init();
	return obj;
}
