$(document).ready(function(){
	styleLangNav();
	
	skBox.run();
	compat();
	
	grants.setup();
	forms.setup();
	results.setup();
	
	sizecompat();
	$(window).resize(function() {
		sizecompat();
	});
	
	//addHover("#enhanceHeader .tip");
	tipsClickActivate("#enhanceHeader .tip");
	
	if($("#iWouldMiss")[0]){
		runTweets();
	}
	//Homepage only
	if($("#videoarea")[0]){
		slideshowVideo.start();
		callouts.setup();
	}
	if($("#manageArea")[0]){
		admin.setup();
	}
});

function styleLangNav(){
	if(getBrowser()!="applemobile"){
		$("#langNav").addClass("js");
		$("#langNav").append("<div class='currLang'>"+$("#langNav ul li a.active").html()+"</div>")	
		$("#langNav").hover(
			function(){ 	if(getWidth()>740){ $("#langNav ul").slideDown(200); }
				},
			function(){  	if(getWidth()>740){ $("#langNav ul").slideUp(200); }
				});
	}
}

function sizecompat(){
	if( $("#rSlider")[0] ){
		//Fix slider
		//DEBGUGING ONLY!  $("#yourResources h4").html( getWidth() );
		if(getWidth()<580){
			$("#yourResources.js #rSlider .sliderCon").css({"width":"215px","margin":"0 auto"});
			results.Yslideramt = 1;
		}
		else if(getWidth()<1000){
			$("#yourResources.js #rSlider .sliderCon").css({"width":"460px","margin":"0 auto"});
			results.Yslideramt = 2;
		}else{
			$("#yourResources.js #rSlider .sliderCon").css({"width":"675px","margin":"0"});
			results.Yslideramt = 3;
		}
		//getWidth()
	}
	if( $("#enhanceHeader .tip")[0] ){
		if(getWidth()<730){
			$("#enhanceHeader .tip").addClass("smallscreenTip");	
		}else{
			$("#enhanceHeader .tip").removeClass("smallscreenTip");	
		}
	}
	if( $("#grantsRequest .progressheader")[0] ){
		if(getWidth()<580){
			$("#grantsRequest .progressheader").addClass("pheaderOriginal").addClass("hide");
			for(var i=0;i<$("#grantsRequest .reqblock").length;i++){
				$("#grantsRequest .reqblock:eq("+i+")").prepend("<div class='progressheader'><h4>"+$("#grantsRequest .progressheader li a:eq("+i+")")[0].innerHTML+"</h4></div>");
			}
		}else{
			$(".pheaderOriginal").removeClass("hide");
			$("#grantsRequest .reqblock .progressheader").addClass("hide");
		}
	}
}	

/* --------------------------------------------- Twitter Feature ----------------------------------------------- */
var tweetCurrent = 0;

function runTweets(){
	$(".fromtwitter").tweet({//username: "TransitionsMVC",//avatar_size: 50,
		join_text: "auto",
		query:"%23mysight",// "%23jqsummit http", // %23jqsummit "from:seaofclouds http" //#mysight //GoodMorning Everyone //%23mysight
		loading_text: "searching twitter...",
		count: 5,
		template: "{text} {user}{time}"//{avatar} {reply_action} {retweet_action}
	}).bind("loaded", function(){
		displayTweets();
	});
}

function displayTweets(){ //		
	var tweetList = new Array();
	for(var i=0;i<$(".fromserver li").length;i++){
		tweetList.push($(".fromserver li")[i].innerHTML);
	}
	for(var i=0;i<$(".fromtwitter li").length;i++){
		var a = "";
		a+= "<em>"+$(".fromtwitter li:eq("+i+") .tweet_text")[0].innerHTML+"</em>";
		a+= "<span>tweeted by "+$(".fromtwitter li:eq("+i+") .tweet_user")[0].innerHTML+" "+$(".fromtwitter li:eq("+i+") .tweet_time")[0].innerHTML+"</span>";
		tweetList.push(a);
	}
	tweetList = tweetList.sort(randomSort);
	
	$("#iWouldMiss #tweetBullets").after("<ul id='tweetStories'></ul>");
	for(var i=0;i<5;i++){
		if(tweetList[i]){
			$("#iWouldMiss #tweetStories").append("<li class='story"+(i+1)+"'>"+tweetList[i]+"</li>");
		}
	}
	switchTweets.run();
	$("#iWouldMiss").slideDown(400);
	
	$("#iWouldMiss #tweetBullets a").click(function(){
		var num = parseInt((""+this.href.split("#story")[1]),10);
		switchTweets.goto(num -1);
		return false;
	});	
}

var switchTweets ={};
switchTweets.index = 0;
switchTweets.auto = true;
switchTweets.run = function(){
	if( switchTweets.auto == true){
	  $("#iWouldMiss #tweetStories").animate({"opacity":"0"},200, function(){
		 $("#iWouldMiss #tweetBullets li").removeClass("active");
		 $("#iWouldMiss #tweetBullets li:eq("+switchTweets.index+")").addClass("active");
		  
		  $("#iWouldMiss #tweetStories li").css({"display":"none"});
		  $("#iWouldMiss #tweetStories li:eq("+switchTweets.index+")").css({"display":"block"});
		  $("#iWouldMiss #tweetStories").animate({"opacity":"1"},200, function(){
			  switchTweets.index++;
			  if(switchTweets.index > ($("#iWouldMiss #tweetStories li").length-1)){
				  switchTweets.index = 0;	
			  }
			  setTimeout(function(){ switchTweets.run(); },7000);	
		  });
	  })
	}
}
switchTweets.goto = function(num){
	switchTweets.auto = false;
	$("#iWouldMiss #tweetStories").animate({"opacity":"0"},200, function(){
		  $("#iWouldMiss #tweetBullets li").removeClass("active");
		  $("#iWouldMiss #tweetBullets li:eq("+num+")").addClass("active");
		  
		  $("#iWouldMiss #tweetStories li").css({"display":"none"});
		  $("#iWouldMiss #tweetStories li:eq("+num+")").css({"display":"block"});
		  $("#iWouldMiss #tweetStories").animate({"opacity":"1"},200);
	});
}

/* --------------------------------------------- Callout Switching ----------------------------------------------- */
var callouts = {};
callouts.t1index = 0;
callouts.t2index = 0;
callouts.setup = function(){
	$("#calloutsection .t1, #calloutsection .t2").addClass("hide");
	$("#calloutLSide, #calloutRSide").append("<div class='arrows'><a class='previous'></a><a class='next'></a></div>");
	callouts.switchCs("#calloutLSide",callouts.t1index);
	callouts.switchCs("#calloutRSide",callouts.t2index);
	
	$("#calloutLSide .previous").click(function(){
		callouts.t1index = callouts.loop(callouts.t1index-1, ($("#calloutsection .t1").length-1));
		callouts.switchCs("#calloutLSide",callouts.t1index);
	});	
	$("#calloutLSide .next").click(function(){
		callouts.t1index = callouts.loop(callouts.t1index+1, ($("#calloutsection .t1").length-1));
		callouts.switchCs("#calloutLSide",callouts.t1index);
	});	
	$("#calloutRSide .previous").click(function(){
		callouts.t2index = callouts.loop(callouts.t2index-1, ($("#calloutsection .t2").length-1));
		callouts.switchCs("#calloutRSide",callouts.t2index);
	});	
	$("#calloutRSide .next").click(function(){
		callouts.t2index = callouts.loop(callouts.t2index+1, ($("#calloutsection .t2").length-1));
		callouts.switchCs("#calloutRSide",callouts.t2index);
	});	
	
	$(".shareBtn .skBox").unbind();
	$(".shareBtn .skBox").click(function(){ //update
		if($("#iWouldMiss form #i_story")[0].value !="I would miss..."){
			$("#submitStoryForm #iwm_story").html( $("#iWouldMiss form #i_story")[0].value );
			$("#submitStoryForm #iwm_story")[0].value = $("#iWouldMiss form #i_story")[0].value; 
		}			
		//"?submitDOM-ID=submitStoryForm&height=230px&width=400"
		skBox.openBox('body',this.href,callouts.popupformcb);
		return false;	
	});
}

callouts.popupformcb = function(){
		//alert("stuff");
	$(".nontweetForm #iwm_submit").click(function(){
		return forms.pv();
	});
	$(".nontweetForm textarea").bind("keypress",function(){
		if(this.value.length >140){
			$(".nontweetForm small").addClass("error");
			$(this).addClass("error");	
		}else{
			$(".nontweetForm small").removeClass("error");
			$(this).removeClass("error");	
		}
	});
	$(".nontweetForm textarea").bind("blur",function(){
		if(this.value.length >140){
			$(".nontweetForm small").addClass("error");
			$(this).addClass("error");	
		}else{
			$(".nontweetForm small").removeClass("error");
			$(this).removeClass("error");	
		}
	});
}

callouts.loop = function(n,total){
	if(n>total){
		n=0;	
	}else if(n<0){
		n=total;	
	}return n;
}

callouts.switchCs = function(con,index){
	$(con+" .callout").animate({"opacity":0},200,function(){
		$(con+" .callout").addClass("hide");
		$(con+" .callout:eq("+index+")").removeClass("hide");	
		$(con+" .callout:eq("+index+")").animate({"opacity":1},200);
	});
}

/* --------------------------------------------- Homepage Video Feature ----------------------------------------------- */

var slideshowVideo ={};
slideshowVideo.index = 0;
slideshowVideo.src = "";
slideshowVideo.start = function(){
	slideshowVideo.src = $("#videoarea .videosrc")[0].innerHTML;
	$("#videoarea .feature video").remove();
	for(var i=0;i<$(".slidelist span").length;i++){
		$(".slideshow").append("<img src='"+$(".slidelist span")[i].innerHTML+"' alt='' class='inactive' />");
	}	
	slideshowVideo.slide();
	$(".slideshow img").click(function(){
		//alert(getBrowser());
		$(".slideshow").remove();
		if(getBrowser()=="webkit"){//If webkit, just use flash
			var flashEmbed ='<embed flashvars="file=../../'+slideshowVideo.src+'&autostart=true&skin=scripts/tirSkin/five.xml" allowfullscreen="true" allowscripaccess="always" id="hVplayer" name="hVplayer" src="content/flash/player.swf" width="600" height="299" />';
			$("#videoarea .feature").append(flashEmbed);
		}else if(getBrowser()=="applemobile"){
			$("#videoarea .feature").append('<video id="hVplayer" height="298" width="600" src="'+slideshowVideo.src+'" autoplay  controls />');
		}
		else{//IF not webkit
			var siteURL = "http://dev.thisisredagency.com/transitions/hsfl";//'http://healthysightforlifefund.org'
			$("#videoarea .feature").append('<video id="hVplayer" height="298" width="600" src="'+slideshowVideo.src+'" autoplay />');//	
			jwplayer('hVplayer').setup({
			  'flashplayer': 'content/flash/player.swf',
			  'id': 'hVplayer',
			  flashvars: "autostart=true",
			  'width': '600',
			  'height': '298',
			  'file': slideshowVideo.src,
			  /*'image': '/thumbs/bunny.jpg',*/
			  'plugins': {
				 'sharing-3': {
					 'link': siteURL,
					 'code': '<embed src="'+siteURL+'/content/flash/player.swf" flashvars="file='+siteURL+'/'+slideshowVideo.src+'&autostart=true&skin='+siteURL+'/scripts/tirSkin/five.xml" width="600" height="299" allowfullscreen="true" />'
				 }
			  }
			});
			jwplayer().play();
		}
				
		$(".slideshow").animate({"opacity":0},800);
	});
}
slideshowVideo.slide = function(){
	$(".slideshow img").css({"z-index":1});
	$(".slideshow img:eq("+slideshowVideo.index+")").removeClass("inactive").css({"z-index":2,"opacity":0});
	$(".slideshow img:eq("+slideshowVideo.index+")").animate({"opacity":1},400,function(){		
		$(".slideshow img").addClass("inactive");
		$(".slideshow img:eq("+slideshowVideo.index+")").removeClass("inactive");
		slideshowVideo.index++;
		if(slideshowVideo.index > ($(".slideshow img").length-1)){
			slideshowVideo.index = 0;	
		}
		setTimeout(slideshowVideo.slide,3000);
	});
}

/* --------------------------------------------- Results & Symptoms ----------------------------------------------- */

var results = {};
results.setup = function() {
	if($("#yourResults")[0]){
		$("#yourResults, #filterContent, #yourResources").addClass("js");
		results.filter("age","other");
		results.filter("issues","other");
		
		$(".filterBox .controls .select b").click(function(){
			$(".filterBox .controls .select").addClass("hover");
		});
		$(".filterBox .controls .select").bind("mouseleave",function(){
			$(".filterBox .controls .select").removeClass("hover");
		});
		
		$(".filterBox .controls .select a").click(function(){
			$(".filterBox .controls .select").removeClass("hover");
			$(".filterBox .controls .select a").removeClass("active");
			$(this).addClass("active");
			$(".filterBox .controls .select b").html(this.innerHTML);
			return false;
		});
		
		$(".filterBox .controls .blueBtn").click(function(){
			$(".filterBox .errorBox").removeClass("error1").removeClass("error2");
			if(!$(".filterBox .controls .select a.active")[0]){
				$(".filterBox .errorBox").addClass("error1");
			}else if(parseInt($("#your_age")[0].value,10) == 0 || !$("#your_age")[0].value){
				$(".filterBox .errorBox").addClass("error2");
			}else{
				var age = "other";// Determine age based on your_age
				if( parseInt($("#your_age")[0].value,10) <18 ){
					age = "kid";	
				}else if( parseInt($("#your_age")[0].value,10) <65 ){
					age = "adult";
				}/*else if( parseInt($("#your_age")[0].value,10) <60 ){

				}*/else{
					age = "senior";
				}
				
				if(age!="kid"){
					results.filter("issues",$(".filterBox .controls .select a.active")[0].href.split("#")[1]);
				}else{
					$("#filterContent .issues").addClass("hide");	
					
					$("#yourResources p").addClass("hide");
					$("#yourResources p."+$(".filterBox .controls .select a.active")[0].href.split("#")[1]).removeClass("hide");
					results.YsliderIndex = 0;
					results.YsliderMove();
				}
				results.filter("age",age);
				results.Yfilter($(".filterBox .controls .select a.active")[0].href.split("#")[1],age);
				results.getSymptoms(age,$(".filterBox .controls .select a.active")[0].href.split("#")[1]);
				
				$("#yourResources.js #rSlider .sliderCon .slider").css({left:"0px"});	
				
				$("#yourResults .selections").remove();
				$("#yourResults").append("<div class='selections'><a href='#removeme' class='selection'>x <span class='uppercase'>"+$(".filterBox .controls .select a.active")[0].href.split("#")[1]+"</span></a><a href='#removeme' class='selection'>x <span class='uppercase'>"+age+"</span></a></div>");
				//selection handler
				$("#yourResults .selection").click(function(){
					$(".filterBox .controls .select a").removeClass("active");
					$("#yourResults .selections").remove();
					results.filter("age","other");
					results.filter("issues","other");
					results.Yfilter("other","");
					$(".filterBox .controls .select b").html($(".filterBox .controls .select b")[0].title );
					$("#your_age")[0].value = "";
					$("#your_age")[0].innerHTML = "";
					$("#yourResources.js #rSlider .sliderCon .slider").css({left:"0px"});
					return false;
				});
			}
			return false;
		});
		
		results.Yslider();
	}
	if($("#recogSymptoms")[0]){
		//replace the images with the flash under #recogSymptoms
		results.getSymptoms("other");
	}
}

results.filter = function(type,filter){
	$("#filterContent ."+type).each(function(){
		$(this).addClass("hide");
		if(this.className.match(filter)){
			$(this).removeClass("hide");	
		}
	});
	if(type!="age"){
		$("#yourResources p").addClass("hide");
		$("#yourResources p."+filter).removeClass("hide");
		results.YsliderIndex = 0;
		results.YsliderMove();
	}
}

results.Yfilter = function(filter,afil){
	if(afil!=""){
		afil = "."+afil;	
	}
	$("#yourResources .slider a").addClass("hide");
	$("#yourResources .slider a."+filter+afil).removeClass("hide");
}

results.YsliderIndex = 0;
results.Yslideramt = 3;
results.Yslider = function(){		
	$("#rSlider .leftBtn").click(function(){
		results.YsliderIndex-=results.Yslideramt;
		results.YsliderMove();
	});
	$("#rSlider .rightBtn").click(function(){
		results.YsliderIndex+=results.Yslideramt;
		results.YsliderMove();
	});
	results.YsliderMove();
	//$("#rSlider b.leftBtn").addClass("disable");
}

results.YsliderMove = function(index){
	$("#rSlider b").removeClass("disable");
	if(results.YsliderIndex<0 || results.YsliderIndex == 0){
		results.YsliderIndex = 0;	
		$("#rSlider b.leftBtn").addClass("disable");
	}
	if( results.YsliderIndex > ($("#yourResources.js #rSlider .slider a:not(.hide)").length -results.Yslideramt) || results.YsliderIndex == ($("#yourResources.js #rSlider .slider a:not(.hide)").length -results.Yslideramt) ){
		results.YsliderIndex = $("#yourResources.js #rSlider .slider a:not(.hide)").length -results.Yslideramt;	
		$("#rSlider b.rightBtn").addClass("disable");
	}
	var pos = "-"+ (results.YsliderIndex*(187+58)) + "px";
	$("#yourResources.js #rSlider .sliderCon .slider").animate({left:pos},600,"easeInOutQuart");
}


results.getSymptoms = function(a,eth){
	var b = results.getRanSymp({age:a,ethnic:eth,symp:"blur"});
	var g = results.getRanSymp({age:a,ethnic:eth,symp:"glare"});
	var c = results.getRanSymp({age:a,ethnic:eth,symp:"cataract"});
	if(b[0].match("landscape")){ //Prevent's over-use of landscapes
		if(g[0].match("landscape")){
			b = results.getRanSymp({age:a,ethnic:eth,symp:"blur"});
			g = results.getRanSymp({age:a,ethnic:eth,symp:"glare",adt:"notLandscape"});
		}
		if(c[0].match("landscape")){
			b = results.getRanSymp({age:a,ethnic:eth,symp:"blur"});
			c = results.getRanSymp({age:a,ethnic:eth,symp:"cataract",adt:"notLandscape"});
		}
	}
	
	$("#recogSymptoms .symptom:eq(0) img, #recogSymptoms .symptom:eq(0) object").remove();
	$("#recogSymptoms .symptom:eq(0)").prepend( 
		results.replaceFlash({	
			src:"content/flash/symptomSim.swf",
			pics:b  }) 
	);
	$("#recogSymptoms .symptom:eq(1) img, #recogSymptoms .symptom:eq(1) object").remove();
	$("#recogSymptoms .symptom:eq(1)").prepend( 
		results.replaceFlash({	
			src:"content/flash/symptomSim.swf",
			pics:g  }) 	
	);
	$("#recogSymptoms .symptom:eq(2) img, #recogSymptoms .symptom:eq(2) object").remove();
	$("#recogSymptoms .symptom:eq(2)").prepend( 
		results.replaceFlash({	
			src:"content/flash/symptomSim.swf",
			pics:c  }) 
	);
}

results.getRanSymp = function(params) {
	var a = "";
	var e = "";
	var s = "";
	var ad = "";
	if(params.ethnic){	e="."+params.ethnic;	}
	if(params.age){	a="."+params.age;	}
	if(params.symp){	s="."+params.symp;	}
	if(params.adt){	ad="."+params.adt;	}
	
	var ar = new Array();
	for(var i=0;i<$(".symptomList "+a+e+s+ad).length;i++){
		ar[i] = $(".symptomList "+a+e+s+ad)[i];	
	}
	ar = ar.sort(randomSort);
	
	return [$(ar[0]).children("b")[0].innerHTML,$(ar[0]).children("i")[0].innerHTML];//[good,bad]
}

results.replaceFlash = function(params){
	var src = params.src+"?blurpic="+params.pics[0]+"&clearpic="+params.pics[1];
	var output = '';
	output += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="310" height="160" id="symptomSimA" align="middle">';
    output += '<param name="movie" value="'+src+'" />';
    output += '<param name="quality" value="high" />';
    output += '<param name="bgcolor" value="#ffffff" />';
    output += '<param name="wmode" value="window" />';
    output += '<param name="scale" value="showall" />';
    output += '<!--[if !IE]>-->';
    output += '<object type="application/x-shockwave-flash" data="'+src+'" width="310" height="160">';
        output += '<param name="movie" value="'+src+'" />';
        output += '<param name="quality" value="high" />';
        output += '<param name="bgcolor" value="#ffffff" />';
        output += '<param name="wmode" value="window" />';
        output += '<param name="scale" value="showall" />';
    output += '<!--<![endif]-->';
        output += '<a href="http://www.adobe.com/go/getflash">';
            output += '<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />';
        output += '</a>';
    output += '<!--[if !IE]>-->';
    output += '</object>';
    output += '<!--<![endif]-->';
	output += '</object>';
	return output;	
}

/* --------------------------------------------- Grants & Form Validation ----------------------------------------------- */
var forms = {};
forms.pv = function(){
	var a = true;
	$("#popContainer *").removeClass("error");
	if(!validationHelper("#popContainer #iwm_story","txt","iwm_story")){	a = false;}
	if( $("#popContainer #iwm_story")[0].value.length>140 ){
		$("#popContainer #iwm_story").addClass("error");
		a = false;
	}
	if(!validationHelper("#popContainer #iwm_source","txt","iwm_source")){	a = false;}
	return a;	
}
forms.cvalidate = function(){
	var a = true;
	$("#contactForm *").removeClass("error");
	if(!validationHelper("#contactForm #fname","txt","fname")){	a = false;}
	if(!validationHelper("#contactForm #lname","txt","lname")){	a = false;}
	if(!validationHelper("#contactForm #email","email","email")){	a = false;}
	if(!validationHelper("#contactForm #comments","txt","comments")){	a = false;}
	return a;	
}
forms.gvalidate = function(){
	var a = true;
	$("#requestForm *").removeClass("error");
	if(!validationHelper("#requestForm #fname","txt","fname")){	a = false;}
	if(!validationHelper("#requestForm #lname","txt","lname")){	a = false;}
	if(!validationHelper("#requestForm #phone","txt","phone")){	a = false;}
	if(!validationHelper("#requestForm #email","email","email")){	a = false;}
	if(!validationHelper("#requestForm #addr1","txt","addr1")){	a = false;}
	if(!validationHelper("#requestForm #city","txt","city")){	a = false;}
	if(!validationHelper("#requestForm #state","txt","state")){	a = false;}
	if(!validationHelper("#requestForm #zip","txt","zip")){	a = false;}
	if(!validationHelper("#requestForm #country","txt","country")){	a = false;}
	if(!validationHelper("#requestForm #datereq","txt","datereq")){	a = false;}
	if(!validationHelper("#requestForm #fundsreq","txt","fundsreq")){	a = false;}
	if(!validationHelper("#requestForm #org","txt","org")){	a = false;}
	if(!validationHelper("#requestForm #comments","txt","comments")){	a = false;}	
	return a;	
}
forms.setup = function (){
	if($("#requestForm")[0]){
		$("#requestForm #submit").click(function(){
			$("#requestForm").removeClass("showerror");
			if(!forms.gvalidate()){
				$("#requestForm").addClass("showerror");
			}
			return forms.gvalidate();
		});
		$("#requestForm input").bind("focus",function(){
			$(".e-all").css({"display":"none"});
			$("#requestForm").removeClass("showerror");
			$(".e-all").css({"display":"block"});
		});
		$(".e-all").bind("mouseenter",function(){
			$(".e-all").css({"display":"none"});
			$("#requestForm").removeClass("showerror");
			$(".e-all").css({"display":"block"});
		});
	}
	if($("#contactForm")[0]){
		$("#contactForm #submit").click(function(){	
			$("#contactForm").removeClass("showerror");
			if(!forms.cvalidate()){
				$("#contactForm").addClass("showerror");
			}
			return forms.cvalidate();
		});
		$("#contactForm input, #contactForm textarea").bind("focus",function(){
			$(".e-all").css({"display":"none"});
			$("#contactForm").removeClass("showerror");
			$(".e-all").css({"display":"block"});
		});
	}
}

var grants = {};
grants.setup = function(){
	if($("#grantsRequest")[0]){
		if(getWidth()>959){
			$("#grantsRequest .reqblock").addClass("hide");	
			$("#grantsRequest .reqblock:eq(0)").removeClass("hide").css({"opacity":"0"});
			grants.gotoBlock("eligibility");
			
			$(".progressheader a, .nextBtn, .backBtn").click(function(){
				grants.gotoBlock(this.href.split("#")[1]);	
				return false;
			});
		}
	}	
	if($("#pastRecipients")[0]){
		if(getWidth()>740){
			// Past Recipients
			$("#pastRecipients").addClass("js");
			$("#pastRecipients").addClass(getBrowser());
			$("#pastRecipients h1").after("<div class='recList'><ul></ul><div class='scrollbar'><div class='scroller'></div></div></div>");
			
			for(var i=0;i<$(".contentarea .rec_panel").length;i++){
				var elem = $(".contentarea .rec_panel")[i];
				if(i%2 == 0){
					$("#pastRecipients .recList ul").append("<li><a href='#c"+(i+1)+"' class='alt'>"+$(elem).children("h3")[0].innerHTML+"</a></li>");
				}else{
					$("#pastRecipients .recList ul").append("<li><a href='#c"+(i+1)+"'>"+$(elem).children("h3")[0].innerHTML+"</a></li>");
				}
				$(elem).addClass("c"+(i+1));
				$(elem).addClass("hide");
			}
			$("#pastRecipients .recList a").click(function(){
				grants.getABlock(this.href.split("#")[1]);	
				$("#pastRecipients .recList a").removeClass("active");
				$(this).addClass("active");
			});
			grants.getABlock("c1");
			
			$("#pastRecipients .recList a:eq(0)").addClass("active");
			
			//make scroller draggable within scrollbar
			$(".scroller").draggable({ axis: 'y', containment: 'parent' });
			//		customScroll.initScroll();
			$( ".scroller" ).bind( "drag", function(event, ui) {
				moveContent(".recList ul", ".recList", $(".scroller").css("top"));
				
			});
		}else{
			for(var i=0;i<$(".contentarea .rec_panel").length;i++){	
				$(".contentarea .rec_panel h3")[i].innerHTML = "<a href='#c"+i+"' style='min-height:30px;'><span class='blueBtn' style='float:left;width:10px;min-height:12px;height:12px;line-height:6px;background-position:0 -5px;margin:3px 8px 0 0;'>+</span>"+$(".contentarea .rec_panel h3")[i].innerHTML+"</a>";
			}
			$(".contentarea .rec_panel h3").addClass("accordion");
			$(".contentarea .rec_panel .txt_content").addClass("hide");
			//$(".contentarea .rec_panel .txt_content:eq(0)").removeClass("hide");
			$(".contentarea .rec_panel h3 a").click(function(){
				$(".contentarea .rec_panel .txt_content").addClass("hide");
				$(this).parent().parent().children(".txt_content").removeClass("hide");
				return false;	
			});
		}
	}
}

function moveContent(toScrl, toScrlcon, moveVal)
{
	var tssize = $(toScrl)[0].clientHeight -$(toScrlcon)[0].clientHeight; //content fullsize - content container size
	//get movevalue for content by comapring to scroll move-value;
	var toscrollps = parseInt(moveVal,10) * tssize/200; 
	$(toScrl).css({'top': "-"+toscrollps+"px"});
}

grants.gotoBlock = function(bname){
	switch(bname){
		case "eligibility":
			$(".progressheader .bg").animate({"width":"25%"},400);
			break;
		case "proposal":
			$(".progressheader .bg").animate({"width":"50%"},400);
			break;
		case "submission":
			$(".progressheader .bg").animate({"width":"75%"},400);
			break;
		case "requestForm":
			$(".progressheader .bg").animate({"width":"100%"},400);
			break;
	}
	$("#grantsRequest .reqblock").animate({"opacity":"0"},400,function(){
		$("#grantsRequest .reqblock").addClass("hide");
		$("#grantsRequest #"+bname).removeClass("hide");
		$("#grantsRequest #"+bname).animate({"opacity":"1"},400);
	});	
}

grants.getABlock = function(c){
	$(".contentarea").animate({"opacity":0},400,function(){
		$(".contentarea .rec_panel").addClass("hide");	
		$(".contentarea ."+c).removeClass("hide");	
		$(".contentarea").animate({"opacity":1},400);
	});
}

/* --------------------------------------------- Administration Dashboard ----------------------------------------------- */

var admin = {};
admin.setup = function(){
	$("#manageArea .t1 .c6 a").click(function(){ //update
		var i = $(this).children(".i-val")[0].innerHTML;
		var selI = $("#manageArea .t1 tbody tr:eq("+i+") .c5 select")[0].selectedIndex;
		
		$("#tipsDyUpdateform #tdf-id")[0].value = $(this).children(".id-val")[0].innerHTML;
		$("#tipsDyUpdateform #tdf-app")[0].value = $("#manageArea .t1 tbody tr:eq("+i+") .c5 option:eq("+selI+")")[0].value; 

		$("#tipsDyUpdateform h3").html("Are you sure you want to update this row?");
		skBox.openBox('body',"?DOM-ID=tipsDyUpdateform&height=160&width=300");
		return false;	
	});
	$("#manageArea .t1 .c7 a").click(function(){ //remove
		$("#tipsDyUpdateform #tdf-da")[0].value = "remove";
		$("#tipsDyUpdateform #tdf-id")[0].value = $(this).children(".id-val")[0].innerHTML;
		$("#tipsDyUpdateform h3").html("Are you sure you want to delete this row?");
		skBox.openBox('body',"?DOM-ID=tipsDyUpdateform&height=160&width=300");
		
		return false;	
	});	
	
	$("#manageArea .t2 .head a").click(function(){ //Add new
		$("#storyDyform #sdf-dba")[0].value = "add";
		var now = new Date();
		$("#storyDyform h3").html("Please choose the month this should be displayed");
		if(!$("#storyDyform .yrbox")[0]){
			$("#storyDyform h3").after("<select name='year' class='yrbox'><option value='"+now.getFullYear()+"' selected>"+now.getFullYear()+"</option><option value='"+(now.getFullYear()+1)+"'>"+(now.getFullYear()+1)+"</option></select>")
		}
		$("#storyDyform #sdf-date").removeClass("hide");		
		skBox.openBox('body',"?DOM-ID=storyDyform&height=160&width=300",admin.popCallback);
		return false;
	});
	
	$("#manageArea .t2 .c5 a").click(function(){ //update
		$("#storyDyform #sdf-dba")[0].value = "update";
		$("#storyDyform #sdf-id")[0].value = $(this).children(".id-val")[0].innerHTML;
		
		$("#storyDyform #sdf-en")[0].value = $(this).parent().parent().children(".c2").children("textarea")[0].value;
		$("#storyDyform #sdf-sp")[0].value = $(this).parent().parent().children(".c3").children("textarea")[0].value;
		$("#storyDyform #sdf-fr")[0].value = $(this).parent().parent().children(".c4").children("textarea")[0].value;
		
		$("#storyDyform h3").html("Are you sure you want to update this row?");
		skBox.openBox('body',"?DOM-ID=storyDyform&height=160&width=300");
		return false;	
	});
	$("#manageArea .t2 .c6 a").click(function(){//remove
		$("#storyDyform #sdf-dba")[0].value = "remove";
		$("#storyDyform #sdf-id")[0].value = $(this).children(".id-val")[0].innerHTML;
		$("#storyDyform h3").html("Are you sure you want to delete this row?");
		skBox.openBox('body',"?DOM-ID=storyDyform&height=160&width=300");
		return false;	
	});	
}

admin.popCallback = function(){
	$("#popContainer select").bind("change",function(){
		//11/29/2011 1:55 PM    mo/day/year    
		$("#popContainer #sdf-da")[0].value=$("#popContainer #sdf-date")[0].value+"/1/"+$("#popContainer .yrbox")[0].value+" 12:00 AM";
	});
}

/* --------------------------------------------- Misc Functions ----------------------------------------------- */
function addHover(This){
	$(This).hover(function(){
			$(this).addClass("hover");
		},function(){
			$(this).removeClass("hover");
		});	
}

function tipsClickActivate(This){
	$(This).click(function(){
		$(this).addClass("hover");
	});
	$(This).bind("blur",function(){
		$(this).removeClass("hover");	
	});
	$(This).bind("mouseleave",function(){
		$(this).removeClass("hover");	
	});
}

function LanguageFix(){
	$(".langFix").each(function(){
		var lang = getLang;
		this.href = replaceParam("l",lang,this.href);
	});	
}

function replaceParam(param,value,string){
	var ns = "";
	var ts = param+"=";
	if(q.indexOf(ts)>-1){
		ns = q.substring(q.indexOf(ts));
		if(ns.indexOf("&")>-1){
			value = ns.substring(ts.length,ns.indexOf("&"));
		}else{
			value = ns.substring(ts.length);
		}
	}
}

/*
skBox.extractQvalue = function(q,param){
	var ns = "";
	var value = ""
	var ts = param+"=";//.length
	if(q.indexOf(ts)>-1){
		ns = q.substring(q.indexOf(ts));
		if(ns.indexOf("&")>-1){
			value = ns.substring(ts.length,ns.indexOf("&"));
		}else{
			value = ns.substring(ts.length);
		}
	}
	return value;
}*/

function getWidth(){
	 var winW = 0
	  if (document.body && document.body.offsetWidth) {
	   winW = document.body.offsetWidth;
	  }
	  if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
	   winW = document.documentElement.offsetWidth;
	  }
	  if (window.innerWidth && window.innerHeight) {
	  	winW = window.innerWidth;
	  }
	  return winW;
}

function randomSort(a,b) {
	return( parseInt( Math.random()*10 ) %2 );
}

function compat(){ //ie/validation edit
	$(".shareoptions iframe").remove();
	$(".shareoptions").prepend('<iframe frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?count=none&amp;url=none&amp;text=%23mysight" style="width:33%; height:20px;overflow:hidden;border:none;"></iframe>');
	
	if($("#enhanceHeader .twocol .col2 .twocol")[0]){
		for(var i=0;i<$("#enhanceHeader .twocol .col2 .twocol .tip").length;i++){
			var highest = $("#enhanceHeader .twocol .col2 .twocol .tip").length;
			$("#enhanceHeader .twocol .col2 .twocol .tip:eq("+i+")").css({"z-index":(highest-i)});
		}
	}
}

function getBrowser(){
	var agent=navigator.userAgent.toLowerCase(); //&& agent.indexOf('iphone')!=-1
	var a ="";
	if(agent.indexOf('applewebkit')!=-1){
		a ="webkit";	
	}
	if(agent.indexOf('iphone')!=-1 || agent.indexOf('ipad')!=-1){ //iPad
		a ="applemobile";
	}
	return a;	
}
