var D = document;
var userAgent = navigator.userAgent.toLowerCase();
window.onload = function() {
    OnPageLoad();
    if (!D) D = document;
    var wtf = document.getElementById('enter');
    voteBooth = document.getElementById('votingBooth');
    if (wtf) F.stepForm(0);


    if (voteBooth) V.init();

}

F = {
	br: navigator.appVersion.match('MSIE'),
	stVis: new Array(0, 0, 0),
	stepForm: function(step, a){
		var mLinks = F.getClass('mLink', 'div');
		var tLinks = F.getClass('tLink', 'div');
		var all = F.getClass('mText', 'div');
		var capsule = 'b' + step, allCaps = F.getClass('clBox', 'div'), stName = 'st' + step, dis = 'dis' + step, type = a, toog = 'tog' + step, lastType = null;
		
		if (step > 0) 
			document.getElementById(dis).style.display = "none";
			F.stepForm.currStep = step;
		
		for (var i = 0; i < all.length; i++) {
			var b = 'tog' + i;
			all[i].style.display = "none";
			document.getElementById(b).innerHTML = '[+]';
			if (document.getElementById('b' + i).className.match(new RegExp('nT')) == null) {
				F.addClass('b' + i, 'nT');
			}
			if ( /*F.stVis[step] == 0 || */F.stepForm.currStep == step) {
				document.getElementById(stName).style.display = "block";
				F.removeClass(capsule, 'nT');
				document.getElementById(toog).innerHTML = '[-]';
				F.stVis[step] = 1;
			}
			else {
				document.getElementById(stName).style.display = "none";
				//document.getElementById(toog).innerHTML= '[+]';
				//F.stVis[step] = 0;
			}
		}
		
		
		//Alternates Step 2 to either view Photo & Essay or Video option
		if (!a || a == 'undefined') {
			a = null;
		}
		else {
			switch (type) {
				case 'photo':
					document.getElementById(type).style.display = "";
					document.getElementById('video').style.display = "none";
					document.getElementById('vFile').value = "";
					lastType = 'photo';
					break;
				case 'video':
					document.getElementById(type).style.display = "";
					document.getElementById('photo').style.display = "none";
					document.getElementById('phFile').value = "";
					document.getElementById('essay').value = "";
					lastType = 'video';
					break;
			}
		}
	},
	getClass: function(className, tag, parent){
		parent = parent || document;
		// Locate all the matching tags
		var allTags = (tag == "*" && parent.all) ? parent.all : parent.getElementsByTagName(tag);
		var matchingElements = new Array();
		
		// Create a regular expression to determine if the className is correct
		className = className.replace(/\-/g, "\\-");
		var regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
		
		var element;
		// Check each element
		for (var i = 0; i < allTags.length; i++) {
			element = allTags[i];
			if (regex.test(element.className)) {
				matchingElements.push(element);
			}
		}
		
		// Return any matching elements
		return matchingElements;
	},
	addClass: function(el, clas){
		document.getElementById(el).className += ' ' + clas;
	},
	removeClass: function(el, clas){
		document.getElementById(el).className = document.getElementById(el).className.replace(new RegExp(clas), '');
	},
	hasClass: function( el, clas ) {
	    if( document.getElementById(el).className.hasIndexOf( clas ) ) {
		    var _theClass = document.getElementById(el).className;
		    var _classes = _theClass.split(" ");
		    for(var _i = 0; _i < _classes.length; _i++) {
			    if( _classes[_i] == clas) {
				    return true;
			    }
		    }
	    }
	    return false;
    },
	isCompatible: function (other) {
	    // Use capability detection to check requirements
	    if( other===false 
	        || !Array.prototype.push
	        || !Object.hasOwnProperty
	        || !document.createElement
	        || !document.getElementsByTagName
	        ) {
	        alert('TR- if you see this message isCompatible is failing incorrectly.');
	        return false;
	    }
	    return true;
	},

	wordCount: function(_this, targetEl, max){
				var charCount = _this.value.length;
				var fullStr = _this.value + " ";
				var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
				var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
				var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
				var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
				var splitString = cleanedStr.split(" ");
				var word_count = splitString.length -1;
				var thisMax = function(){
					 var a = left_trimmedStr.split(' ');
					 a.pop(); a.pop();
					 return a.join(' ');
				}();
				if(word_count > max){
					_this.value=thisMax;
					targetEl.value='0';
				}else{
					targetEl.value=max - word_count;
				}
	},
	bookMark: function(url, title){
		var a = title.split('/');
		var t = '2009 HIV Photo and Video Contest - ' + a[2];
		var ua=navigator.userAgent.toLowerCase();
        var isKonq=(ua.indexOf('konqueror')!=-1);
        var isSafari=(ua.indexOf('webkit')!=-1);
        var isMac=(ua.indexOf('mac')!=-1);
        var buttonStr=isMac?'Command/Cmd':'CTRL';
        
		if (window.sidebar) // firefox
			window.sidebar.addPanel(t, url, "");
		else if(window.opera && window.print){ // opera
			var elem = document.createElement('a');
			elem.setAttribute('href',url);
			elem.setAttribute('title',t);
			elem.setAttribute('rel','sidebar');
			elem.click();
		} 
		else if(document.all)// ie
			window.external.AddFavorite(url, t);
		else if(window.opera && window.print) {
	    prepBookmarkLink();

        var a=document.createElement('a');
        a.href=location.href;      
        document.write('<a href = "'+url+'" title="'+title+'" rel="sidebar"></a>');
        a.rel='sidebar'; // this makes it work in Opera 7+
        a.click();   
    }		

    else if(window.external && (!document.createTextNode ||
      (typeof(window.external.AddFavorite)=='unknown'))) {
     
        // IE4/Win generates an error when you
        // execute "typeof(window.external.AddFavorite)"
        // In IE7 the page must be from a web server, not directly from a local 
        // file system, otherwise, you will get a permission denied error.
        window.external.AddFavorite(url, title); // IE/Win
    } else if(isKonq) {
      alert('You need to press CTRL + B to bookmark our site.');
    } else if(window.opera) {
     alert("dfsdf");
      void(0); // do nothing here (Opera 7+)
//return true;
    } else if(window.home || isSafari) { // Firefox, Netscape, Safari, iCab
      alert('You need to press '+buttonStr+' + D to bookmark our site.');
    } else if(!window.print || isMac) { // IE5/Mac and Safari 1.0
      alert('You need to press Command/Cmd + D to bookmark our site.');    
    } else {
      alert('In order to bookmark this site you need to do so manually '+
        'through your browser.');
    }
			
	return false;
	},
	getCookie: function(Name) {
	  var search = Name + "="
	  var returnvalue = "";
	  if (document.cookie.length > 0) {
	    offset = document.cookie.indexOf(search)
	    // if cookie exists
	    if (offset != -1) { 
	      offset += search.length
	      // set index of beginning of value
	      end = document.cookie.indexOf(";", offset);
	      // set index of end of cookie value
	      if (end == -1) end = document.cookie.length;
	      returnvalue=unescape(document.cookie.substring(offset, end))
	      }
	   }
	  return returnvalue;
	}
}

//Generic Animation Object
A = {
	fadeIn: function(el, grains, time, powr){
		if(el.fadeInInt) clearInterval(el.fadeInInt);
		var actStep = 0;
		el.fadeInInt = setInterval(
			function(){
				el.curStep = A.easeInOut(0,100,grains,actStep,powr);
				if (F.br) {
					el.style.filter = 'alpha(opacity =' + el.curStep + ')';
				}else{
					el.style.opacity = el.curStep / 100;
				}
				actStep++;
				if(actStep > grains) clearInterval(el.fadeInInt);
			},
			time
		);
	},
	fadeOut: function(el, grains, time, powr){
		if(el.fadeOutInt) clearInterval(el.fadeOutInt);
		var actStep = 0;
		el.fadeOutInt = setInterval(
			function(){
				el.curStep = A.easeInOut(70, 0, grains, actStep, powr);
				if(F.br){
					el.style.filter = 'alpha(opacity=' + el.curStep + ')';
				}else{
					el.style.opacity = el.curStep / 100;
				}
				actStep++;
				if(actStep > grains){
					clearInterval(el.fadeOutInt);
					el.style.display = "none";
					
				} 
			},
			time
		);
	},
	slidePos: function(el,startPos,endPos,grains,time,powr) {
		if (el.slidePosInt) window.clearInterval(el.slidePosInt);
		var actStep = 0;
		el.slidePosInt = window.setInterval(
			function() {
				el.currentPos = [
					A.easeInOut(startPos[0],endPos[0],grains,actStep,powr),
					A.easeInOut(startPos[1],endPos[1],grains,actStep,powr)
					];
				el.style.left = el.currentPos[0]+"px";
				el.style.top = el.currentPos[1]+"px";
				actStep++;
				if (actStep > grains) window.clearInterval(el.slidePosInt);
			}
			,
			time
		);
	},
	easeInOut: function(minValue,maxValue,totalSteps,actualStep,powr) {
		//Generic Animation Step Value Generator By www.hesido.com
		var delta = maxValue - minValue;
		var stepp = minValue+(Math.pow(((1 / totalSteps)*actualStep),powr)*delta);
		return Math.ceil(stepp);
	}
}

V = {
	//Voting Object
	radioShields: null,
	popWindow: null,
	startPos: new Array(),
	callShield: null,
	selectedId: null,
	//When the Vote page loads..
	init: function(){
		entries = F.getClass('entryItem', 'div'); entPics = F.getClass('entryPic', 'img'); pData = F.getClass('popData', 'div'); options = F.getClass('lockVote', 'input');
		V.radioShields = F.getClass('voteShield', 'div');
		V.popWindow = document.getElementById('votePop');
		V.callShield = document.getElementById('callShield');
		for(var i = 0; i < entries.length; i++){
			options[i].setAttribute('id', 'opt-'+i);
			entries[i].setAttribute('id', 'entry'+i);
			entPics[i].setAttribute('id', i);
			pData[i].setAttribute('id', 'pop'+i);
			entPics[i].onmouseover = this.mEnter;
			entPics[i].onmouseout = this.mLeave;
			options[i].onclick = this.lockVote;
			
			//Stupidly set left position of popData depending on its index #
			if(i == 2 || i == 7){
				if(F.br){
					pData[i].style.marginLeft = '-310px';
				}else{
					pData[i].style.marginLeft = '-190px';
				}
			}
			if(i == 3 || i == 4 || i == 8 || i == 9){
				if(F.br){
					pData[i].style.marginLeft = '-503px';
				}else{
					pData[i].style.marginLeft = '-384px';
				}
			}
			if(i > 4){

					pData[i].style.marginTop = '-342px';
	
			}
		}
	},
	//When you rollover on an Image..
	mEnter: function(event){
		var entId = this.getAttribute('id');
		var popData = document.getElementById('pop'+entId);

		V.callShield.style.display="block";
		for(var i = 0; i < V.radioShields.length; i++){
			V.radioShields[i].style.display="block";
			if (F.br) {
					entPics[i].style.filter = 'alpha(opacity =50)';
				}else{
					entPics[i].style.opacity = 0.5;
				}
		}
		popData.style.display = 'block';
		//A.fadeIn(popData, 5, 5, 0.5);
	},
	//When you roll off an Image..
	mLeave: function(event){
		var entId = this.getAttribute('id');
		var popData = document.getElementById('pop'+entId);
		//A.fadeOut(popData, 10, 10, 0.5);
		popData.style.display = 'none';
		V.callShield.style.display="none";

		for(var i = 0; i < V.radioShields.length; i++){
			V.radioShields[i].style.display="none";
			if (F.br) {
					entPics[i].style.filter = 'alpha(opacity =100)';
				}else{
					entPics[i].style.opacity = 1;
				}
		}
	},
	lockVote: function(event){
		var entId = this.getAttribute('id').split('-')[1];
		
		//Css Method
		F.addClass('votingBooth', 'locked'); F.addClass('entry'+entId, 'selected');
		V.selectedId = entId;
		document.getElementById('voteBtn').style.display = "block";
		document.getElementById('disableVote').style.display = "none";
		
		//JS method
		V.callShield.style.display="block";
		V.callShield.onmousedown = V.resetForm;
		
		for(var i = 0; i < V.radioShields.length; i++){
			entPics[i].onmouseover = null;
			entPics[i].onmouseout = null;
			
			if (i != entId) {
				entPics[i].onmousedown = V.resetForm;
				V.radioShields[i].onmousedown = V.resetForm;	
				V.radioShields[i].style.display = "block";
				if (F.br) {
					entPics[i].style.filter = 'alpha(opacity =50)';
				}
				else {
					entPics[i].style.opacity = 0.5;
				}
			}
		}
	},
	resetForm: function(event){
		F.removeClass('votingBooth', 'locked');
		voteBooth.onmousedown = null;
		document.getElementById('voteBtn').style.display = "none";
		document.getElementById('disableVote').style.display = "block";
		V.callShield.onmousedown = V.resetForm;
		for(var i = 0; i < V.radioShields.length; i++){
			V.callShield.style.display="none";
			F.removeClass('entry'+V.selectedId, 'selected')
			entPics[i].onmousedown = null;
			V.radioShields[i].onmousedown = null;
			entPics[i].onmouseover = V.mEnter;
			entPics[i].onmouseout = V.mLeave;
			V.radioShields[i].style.display = "none";
			options[i].checked = false;
			if (F.br) {
				entPics[i].style.filter = 'alpha(opacity =100)';
			}
			else {
				entPics[i].style.opacity = 1;
			}
		}
	},
	chkVote: function(){
		if(F.getCookie('voted') == ''){
            var photoID;
         
            for (i = 0 ; i < document.aspnetForm.vote.length; i++)
            {
                if (document.aspnetForm.vote[i].checked == true)
                    photoID = i;
            }
            
	        __context.GetServiceClientProxy("RPC2SiteServices").SubmitPublicVoting(photoID);
		                    	      
   	         var date = new Date ();
   	         date.setTime(date.getTime()+(20000*24*60*60*1000));
             var expires = ";expires=" + date.toGMTString();
   	         document.cookie = "voted=" + photoID + expires + ";path=/";

            if(photoID == 0)
            {
                window.location = 'VoteConfirmation1.aspx';
            }
            else if(photoID == 1)
            {
                window.location = 'VoteConfirmation2.aspx';
            }
            else if(photoID == 2)
            {
                window.location = 'VoteConfirmation3.aspx';
            }
            else if(photoID == 3)
            {
                window.location = 'VoteConfirmation4.aspx';
            }
            else if(photoID == 4)
            {
                window.location = 'VoteConfirmation5.aspx';
            }
            else if(photoID == 5)
            {
                window.location = 'VoteConfirmation6.aspx';
            }
            else if(photoID == 6)
            {
                window.location = 'VoteConfirmation7.aspx';
            }
            else if(photoID == 7)
            {
                window.location = 'VoteConfirmation8.aspx';
            }
            else if(photoID == 8)
            {
                window.location = 'VoteConfirmation9.aspx';
            }
            else if(photoID == 9)
            {
                window.location = 'VoteConfirmation10.aspx';
            }
            
		}
		else
		{
			 window.location = 'VoteConfirmation.aspx';
		}
	}
}
function setBrowserSettings() {

    var width = screen.width;
    width = width - 21;
    var detect = navigator.userAgent.toLowerCase();
    var bVer = parseInt(navigator.appVersion);

    if ((detect.indexOf('msie 6.0') + 1)) {
        if ((screen.width == 800) && (screen.height == 600)) {
            document.getElementById('divmain').style.width = "1007px"
        }
        else {
            document.getElementById('divmain').style.width = width;
        }
    }
    else {
        document.getElementById('divmain').style.width = "100%";
    }
}