/*_------------------------------ REFRESH WINDOW ---------------------------------*/
function refresh()
{
    window.location.reload( false );
}
/*_------------------------------ COLLAPSABLE ITEMS ---------------------------------*/
function expand(id)
{
	if (document.getElementById(id+"_content").style.display == 'none'){
		document.getElementById(id+"_content").style.display='block';
		document.getElementById(id+"_link").setAttribute((document.all ? "className" : "class"), "collapse");
	}else{
		document.getElementById(id+"_content").style.display='none';
		document.getElementById(id+"_link").setAttribute((document.all ? "className" : "class"), "expand");
	}
	document.getElementById("contentLeft").style.height = "100%";
}
/*_------------------------------ SECONDARY NAV FOR SITES ---------------------------------*/
function showSecondaryNav(nav)
{
	nav = $(nav);
	var dd = $('ul', nav);
	var items = $('li', dd);
	// check if vertical or horizontal nav
	if($('#headerLinks').css('min-height') == "400px"){
		dd.css({left: 0-nav.position().left+nav.outerWidth(), top: 0});
		dd.stop(true,true).slideDown(300);
		nav.hover(function() {
	
		},function(){
			dd.stop(true,true).delay(500).slideUp(300);
		});
	}else{
		dd.stop(true,true).slideDown(250);
		dd.css({left: 0, top: $('a', nav).outerHeight()});
		nav.hover(function() {
	
		},function(){
			dd.stop(true,true).slideUp("slow");
		});
	}
	
}
/*_------------------------------ NEW APP WINDOW ---------------------------------*/

function launchApp(url,swfID) 
{
	var w = screen.width-15;
	var h = screen.height-90;
	var xPos = (screen.width-w)/2;
	var yPos = (screen.height-h)/2;
	var newWin = window.open(url,'app','fullscreen=no,menubar=no,location=no,toolbar=no,resizable=yes,status=no,width='+w+',height='+h+',left='+xPos+',top='+yPos+'');
	if( !newWin ){
		document.getElementById(swfID).openWindowFromSwf(url);
	}else{
		if(typeof(newWin)!='undefined' && !newWin.closed) {
			newWin.blur();
		}else {
			var newWin = window.open(url,'app','fullscreen=no,menubar=no,location=no,toolbar=no,resizable=yes,status=no,width='+w+',height='+h+',left='+xPos+',top='+yPos+'');
		}
		// Just in case width and height are ignored
		//newWin.resizeTo(w, h);
		// Just in case left and top are ignored
		//alert(xPos+", "+yPos);
		newWin.moveTo(xPos, yPos);
		newWin.focus();
	}
	return false;
}
/*_------------------------------ GET URL VARIABLES ---------------------------------*/
function getURLVar(urlVarName)
{
	//divide the URL in half at the '?'
	var urlHalves = String(document.location).split('?');
	var urlVarValue = '';
	if(urlHalves[1]){
		//load all the name/value pairs into an array
		var urlVars = urlHalves[1].split('&');
		//loop over the list, and find the specified url variable
		for(i=0; i<=(urlVars.length); i++){
			if(urlVars[i]){
				//load the name/value pair into an array
				var urlVarPair = urlVars[i].split('=');
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
					//I found a variable that matches, load it's value into the return variable
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	return urlVarValue;   
}
/*_------------------------------ LOGOUT ---------------------------------*/
function logout()
{
	var info = "action=userLogout";
	// send to php
	sendReq("/resources/php/ajax.php","LogoutStatus(req.responseText)",info);
}

function LogoutStatus(status){
	refresh();	
}
/*_------------------------------ FIX BUTTON ALIGNMENTS ---------------------------------*/
function buttonFix(btn){
	btn.find("ul.button").width(btn.find("ul.button").width()+10);
	btn.width(btn.find("ul.button").width());
}
/*_------------------------------ ROLLOVERS ---------------------------------*/
function renderRollOvers(target){
	$(".rollover", target).wrap("<div class='rollover-holder' style='position:relative;'>");
	$(".rollover-holder", target).each(function(){
		var item = $(this);
		item.width($('.rollover',item).outerWidth());
		item.attr("id", $('.rollover', item).attr("name"));
		//$('.rollover', item).attr("id","");
		if($('.rollover', item).css('float') !== 'none'){
			item.css({float : $('.rollover', item).css('float')});
		}
		$('.rollover', item).css({"z-index" : "1", "position" : "relative"});
		item.append("<div class='bg'></div>");
		$('.bg',item).css('margin-left',$(".rollover", target).css('margin-left'));
		item.hover(function(){
			// b/c IE is stupid
			if($.browser.msie) {
				$(".bg", item).show();
				$(".rollover", item).css({color:"#FFF"});
			}else{
				$(".bg", item).stop(true,true).fadeIn();
				$(".rollover", item).stop(true,true).animate({color:"#fff"});
			}	
		},
		function(){
			if($.browser.msie) {
				$(".bg", item).hide();
				$(".rollover", item).css({color:$("#content").css("color")});
			}else{
				$(".bg", item).stop(true,true).fadeOut();
				$(".rollover", item).stop(true,true).animate({color:$("#content").css("color")});
			}
		});
	});
}
/*_------------------------------ ON LOAD ---------------------------------*/
$(window).load( function() {
	// fix buttons
	$('.buttonWrapper').each(function(s){ buttonFix($(this)); });
	secureForms();
  	// style forms
 	createPhotoGrid();
 	createAlbumLinks();
	renderRollOvers('#content');
	renderDownloads();
 	// add slide show if flash isn't present
	$('.slideshow').not(".block").slideshow();
	// round image corners
	if (!$.browser.msie) {
		$('.rounded-img').wrap(function() {
			return '<span style="background-image:url(' + $(this).attr('src') + '); height: '+ $(this).height() + 'px; width: '+ $(this).width() + 'px;" class="rounded" />';
		});
	}
	// render billboard
	$('.billboard-holder img:gt(0)').hide();
    setInterval(function(){
      $('.billboard-holder :first-child').fadeOut('slow')
         .next('img').fadeIn('slow')
         .end().appendTo('.billboard-holder');}, 
      $('.billboard-holder').dataset('timing'));
	// fix input placeholders
	$('[placeholder]').addPlaceholder();
	// RENDER SWF VIDEO EMBEDS
	$('.videoplayer').each(function() {
		var block = $(this);
		//embed swf
		var player = block.find('.player');
		if(player.hasClass('embed-swf')){
			player.flash({
				swf: player.data('source'),
				width: player.data('width'),
				height: player.data('height')
			});
			player.removeClass('embed-swf');
		}
	});
	// RENDER SHARE BUTTONS
	$('.share-buttons').each(function(){
		var shareButton = $(this);
		// get the url being shared
		var shareURL = $(this).data('url');
		// get the twitter count
		$.getJSON("http://urls.api.twitter.com/1/urls/count.json?url="+shareURL+"&callback=?", function(data) {
			shareButton.find('#twitter_count').html(data.count);
		});
		// get the facebook count
		$.getJSON("https://graph.facebook.com/"+shareURL+"&callback=?", function(data) {
			if(data.shares == undefined) data.shares = 0;
			shareButton.find('#facebook_count').html(data.shares);
		});
		// create plusone hover button
		shareButton.find('#plusone-wrapper').hover(function(){
			$(this).find('#plusone-holder').show();
		},function(){
			$(this).find('#plusone-holder').hide();
		});
	});

})
/*_------------------------------ FORMS ---------------------------------*/
function secureForms()
{
	// remove any javascript required warnings
	$('.warning').remove();
	// get token
	$.get("/resources/site/utils/token.php",function(txt){
	$(".secure").append('<input type="hidden" name="ts" value="'+txt+'" />');
	});
}
function checkContactForm(form){
	var form = $('#'+form);
	$(".submitButton", form).hide();
	var action = "contactForm";
	var formArray = new Array("name","email","content");
	var valueArray = new Array();
	var err = "none";
	// check to see if fields are filled in
	for(i=0;i<formArray.length;i++){
		if ($('[name='+formArray[i]+']', form).val() == "" || $('[name='+formArray[i]+']', form).val() == $('[name='+formArray[i]+']', form).attr('placeholder')){
			$('[name='+formArray[i]+']', form).removeClass().addClass("req");
			err = "error";
		}else{
			$('[name='+formArray[i]+']', form).removeClass().addClass("formInput");
			valueArray.push(escape($('[name='+formArray[i]+']', form).val()));
		}
	}
	
	if (err == "none"){
		formArray.push("phone");
		valueArray.push(escape(($('[name=phone]',form).val() == $('[name=phone]', form).attr('placeholder'))? "":$('[name=phone]',form).val()));
		formArray.push("titleArray");
		valueArray.push(escape($('[name=titleArray]',form).val()));
		formArray.push("userID");
		valueArray.push($('[name=userID]',form).val());
		formArray.push("ts");
		valueArray.push($('[name=ts]',form).val());
		formArray.push("to");
		valueArray.push(escape($('[name=to]',form).val()));
		formArray.push("subject");
		valueArray.push(escape($('[name=subject]',form).val()));
		// build string to send to funciton
		var info = "action="+action;
		for (i=0;i<formArray.length;i++){
			info += "&"+formArray[i]+"="+valueArray[i];
		}
		$.post('/resources/site/utils/ajax.php', info, function(status) {
			if(status == "suspicious"){
				$("#status", form).fadeIn(300);
				$("#status", form).html("<div class='alert_error'>This email could not be sent at this time.</div>");
			}else if(status == "time"){
				("#status", form).fadeIn(300);
				$("#status", form).html("<div class='alert_error'>Please refresh this page and try again.</div>");
			}else if(status == "success"){
				$("#status", form).fadeIn(300);
				$("#status", form).html("<div class='alert_success'>Your message was sent.</div>");
				$(".formContent", form).hide();
			}else{
				$("#status", form).fadeIn(300);
				$("#status", form).html("<div class='alert_error'>An error occurred. Please try again later.</div>");
			}
			$(".submitButton", form).show();
		});
	}else{
		$("#status", form).fadeIn(300);
		$("#status", form).html("<div class='alert_attention'>Please fill in required fields.</div>");
		$(".submitButton", form).show();
	}
}
function checkSubscribeForm(form){
	var form = $('#'+form);
	$(".submitButton", form).hide();
	var err = "";
	form.find(".required").each(function(){
		if($(this).val() == ""){
			err = "fill in all required information";
			$(this).removeClass('formInput').addClass('req');
		}else{
			$(this).removeClass('req').addClass('formInput');	
		}
	});
	if(err !== ""){
		$("#status", form).fadeIn(300);
		$("#status", form).html("<div class='alert_attention'>"+err+"</div>");
		$(".submitButton", form).show();	
	}else{
		var opt = new Object();
		opt.email_address = (form.find('#email-input').val() == form.find('#email-input').attr('placeholder'))? "":form.find('#email-input').val();
		opt.first_name = (form.find('#first-input').val() == form.find('#first-input').attr('placeholder'))? "":form.find('#first-input').val();
		opt.last_name = (form.find('#last-input').val() == form.find('#last-input').attr('placeholder'))? "":form.find('#last-input').val();
		
		form.find("#anim").show();
		form.find("#input-buttons").hide();
		$.post('/resources/site/utils/ajax.php', "action=subscribeForm&list="+form.dataset('list')+"&options="+JSON.stringify(opt)+"&ts="+$('[name=ts]',form).val(), function(status) {
			if(status == "suspicious"){
				$("#status", form).fadeIn(300);
				$("#status", form).html("<div class='alert_error'>This email could not be sent at this time.</div>");
			}else if(status == "time"){
				("#status", form).fadeIn(300);
				$("#status", form).html("<div class='alert_error'>Please refresh this page and try again.</div>");
			}else if(status == "success"){
				$("#status", form).fadeIn(300);
				$("#status", form).html("<div class='alert_success'>Your email was added.</div>");
				$(".formContent", form).hide();
			}else{
				$("#status", form).fadeIn(300);
				$("#status", form).html("<div class='alert_error'>An error occurred. Please try again later.</div>");
			}
			$(".submitButton", form).show();
		});
	}
}
/*_------------------------------ CREATE PHOTO GRIDS ---------------------------------*/
function createPhotoGrid()
{	
	//$('img','.imageGrid').load(function(){alert('test');
		$('.imageGrid').each(function(s){
			$('.grid', $(this)).fadeIn();
			var gridID = $(this).attr('id').split('imageGrid_').join('');
			// get current scale
			var currentSize = $(this).find('.scale-image').width();
			var currentScale = currentSize/150;
			// b/c IE is stupid
			if($.browser.msie) {
				$(this).find('#imageGridSlider').slider({
					value: currentScale,
					step:.01,
					round: 2,
					from: .25,
					to: 1,
					limits: false,
					callback: function(ui){
						scaleIt(ui,$('#imageGrid_'+gridID));
					}
				});
				scaleIt(currentScale,$('#imageGrid_'+gridID));
			}else{
				$(this).find('#imageGridSlider').slider({
					value: currentScale,
					step:.01,
					round: 2,
					from: .25,
					to: 1,
					limits: false,
					onstatechange: function(ui){
						scaleIt(ui,$('#imageGrid_'+gridID));
					}
				});
			}
			positionThumbs($('#imageGrid_'+gridID));
			$('#imageGrid_'+gridID).find(".scale-image").hover(function() {
				$(this).stop().animate({ marginTop: "-5px"}, 200);
			},function(){
				$(this).stop().animate({ marginTop: "0px"}, 300);
			});
			
				
			$("a[rel='group"+gridID+"']").colorbox({current:"{current} of {total}"});
		});
	//});
	
}
function scaleIt(v,grid) 
{
	//if(v !== parseFloat(grid.dataset("scale"))){
		// Remap the 0-1 scale to fit the desired range
		floorSize = .26;
		ceilingSize = 1.0;
		
		grid.find(".scale-image").each(function(s) {
			var thumb = $(this);
			var image = $("img", thumb);
			thumb.width(v*150);
			thumb.height(v*150);
			if(image.width() <= image.height()){
				image.width((image.width()*(v*113))/image.height());
				image.height(v*113);
			}else{
				image.height((image.height()*(v*150))/image.width());
				image.width(v*150);
			}
			grid.dataset("scale",v);
		});
		
		grid.find(".scale-image.crop-square").each(function(s) {
			var thumb = $(this);
			var image = $("img", thumb);
			thumb.width(v*150);
			thumb.height(v*150);
			if(image.width() >= image.height()){
				image.width((image.width()*(v*150))/image.height());
				image.height(v*150);
			}else{
				image.height((image.height()*(v*150))/image.width());
				image.width(v*150);
			}
			grid.dataset("scale",v);
		});
		
		positionThumbs(grid);
	//}
}
function positionThumbs(g)
{
	var grid = g.find(".grid").first();
	var thumbs = g.find(".scale-image");
	var rowCount = 0;
	var xPos = 0;
	var yPos = 0;
	var pad = 10;
	thumbs.each(function(s){
		var thumb = $(this);
		thumb.css({top: yPos, left: xPos});
		var image = thumb.find("img");
		thumb.find("a").css({position:"relative", left:(thumb.width()-image.width())/2, top: (thumb.height()-image.height())/2 });
		xPos += thumb.width()+pad;
		rowCount++;
		grid.height(yPos+thumb.height()+15);
		if(xPos+thumb.width()+pad > grid.outerWidth()){
			rowCount = 0;
			xPos = 0;
			yPos += thumb.height()+pad;
		}
	});
	// if controls are visible add it to the height
	if(g.find(".photoGridControls").css("display") == "block"){
		grid.height(grid.height()+g.find(".photoGridControls").outerHeight());
	}
}
/*_------------------------------ CREATE ALBUM LINKS ---------------------------------*/
function createAlbumLinks()
{	
	$('.albumLinks').each(function(s){
		var main = $(".albumLinks");
		var mask = $(".album-links-mask");
		var thumbs = $(".album-link");
		var controls = $(".album-links-controls", main);
		var pad = 10;
		var w = $(".album-link").width()+pad;
		var maskWidth = main.parent().width();
		var maskHeight = (maskWidth > 300)? 150:470;
		var labels = ($(".album-links-label").css('display') == "block")? true:false; // tells wether the albums have labels or not
		if(!labels && maskHeight == 470){
			maskHeight = 410;
		}else if(!labels){
			maskHeight = 100;
		}
		var rowHeight = (labels)? 115:100; // set row height depending on labels
		var perRow = Math.floor(maskWidth/w);
		var perColumn = Math.floor(maskHeight/rowHeight);
		var perPage = perColumn*perRow;

		var rows = 0;
		var columns = 0;
		var count = 0;
		// set dataset variables
		controls.dataset("current",0);
		controls.dataset("total", Math.ceil(thumbs.length/perPage));
		var currentAlbumPage = parseInt(controls.dataset("current"));
		var totalAlbumPages = parseInt(controls.dataset("total"));
		// position controls
		controls.width((w*perRow)-pad);
		if(totalAlbumPages > 1){
			$('.album-links-pages').html((currentAlbumPage+1)+" of "+totalAlbumPages);	
		}else{
			$('.album-links-pages').hide();
			$('.rightArrow', controls).hide();
			$('.leftArrow', controls).hide();
		}
		
		mask.css({overflow: "hidden"});
		mask.height(maskHeight);
		mask.width(maskWidth);
		
		thumbs.each(function(s){
			var thumb = $(this);
			thumb.css({
					  top: rows*rowHeight,
					  left: count*w+(columns*maskWidth)
					  });
			if(count == perRow-1){
				count = 0;
				rows++;
				if(rows == perColumn){
					rows = 0;
					columns++;
				}
			}else{
				count++;	
			}
			
		});
		
		mask.find(".album-link").fadeIn(300);
		mask.find(".album-link").hover(function() {
			$(this).stop().animate({ marginTop: "-3px"}, 200);
		},function(){
			$(this).stop().animate({ marginTop: "0px"}, 300);
		});
		
	});
}
function changeAlbumLinksPage(type)
{
	var controls = $('.album-links-controls');
	var currentAlbumPage = parseInt(controls.dataset("current"));
	var totalAlbumPages = parseInt(controls.dataset("total"));
	if(type == "next"){
		// check if next page exists
		if(currentAlbumPage < totalAlbumPages-1){
			currentAlbumPage++;
			// hide next button if last page
			$('.leftArrow', controls).show();
			if(currentAlbumPage >= totalAlbumPages-1){
				$('.rightArrow', controls).hide();
			}else{
				$('.rightArrow', controls).show();
			}
		}
	}else{
		if(currentAlbumPage > 0){
			currentAlbumPage--;	
		}
		// hide prev button if first page
			$('.rightArrow', controls).show();
			if(currentAlbumPage <= 0){
				$('.leftArrow', controls).hide();
			}else{
				$('.leftArrow', controls).show();
			}
	}
	controls.dataset("current",currentAlbumPage);
	$('.album-links-pages').html((currentAlbumPage+1)+" of "+totalAlbumPages);
	$(".album-links-holder").stop().animate({ left: 0-(currentAlbumPage*$(".album-links-mask").width())}, 200);
}

/*_------------------------------ DOWNLOAD BUTTONS ---------------------------------*/
function renderDownloads()
{
	$(".download-button").click(function(){
		var item = $(this);						  
		//if($(this).dataset("type") == "image" || $.browser.msie || $.browser.safari){
		window.open($(this).dataset("url"));
		//}else{
		//	$('#download-iframe').attr('src', $(this).dataset("url"));
		//};
		// increment download
		$.post('/resources/site/utils/ajax.php', 'action=fileDownload&file='+$(this).dataset("fileID"), function(result) {
			
		});
	});
	$('a','#content').each(function(){
		// check for file links
		var item = $(this);
		if(item.attr('href') && item.attr('href').indexOf("file:") !== -1){
			var fileID = item.attr('href').split('file:').join('');
			$.post('/resources/site/utils/ajax.php', 'action=getFileURL&file='+fileID, function(result) {
				item.attr('href',result);	
				item.attr('class','download-link');
			});
		}
	});
}
