var pages=[];
	pages['splash']={"div":"switch","title":""};
	pages['reels']={"div":"showreels","title":"recent work"};
	pages['newsArc']={"div":"newsArchive","title":"news archive"};
	pages['reelArc']={"div":"reelArchive","title":"spots archive"};
	pages['editorReel']={"div":"reelsBox","title":""};
	pages['studioLink']={"div":"studioLinkBox","title":"studio link"};
	pages['forms']={"div":"formsBox","title":""};
	pages['info']={"div":"infoBox","title":"technical specs"};
	pages['contact']={"div":"contactBox","title":"contact"};
	pages['login']={"div":"loginBox","title":"login page"};
	pages['MVS']={"div":"musicVideos","title":"music videos"};
var oldPage="splash";
var currentPage="splash";
var editorId;
var months=[];
	months["01"]="Jan";
	months["02"]="Feb";
	months["03"]="Mar";
	months["04"]="Apr";
	months["05"]="May";
	months["06"]="Jun";
	months["07"]="July";
	months["08"]="Aug";
	months["09"]="Sep";
	months["10"]="Oct";
	months["11"]="Nov";
	months["12"]="Dec";
var editors=[];
	editors[1]={"name":"company reel","position":""};
	editors[5]={"name":"eric whipp","position":"colourist"};
	editors[4]={"name":"wade odlum","position":"colourist"};
	editors[7]={"name":"tricia hagoriles","position":"colourist"};
	editors[8]={"name":"conor fisher","position":"colourist"};
	editors[2]={"name":"darren achim","position":"flame artist"};
	editors[3]={"name":"rob fisher","position":"flame artist"};
var RESIZE_PERCENT=1;
var RESIZE_DELAY=1;
var MIN_FONT=65;
var MIN_GRID_HEIGHT=260;
var ARC_SLIDE_DELAY=1000;
var MENU_CHANGE=120;
var ar_old;
var ar_new;
var searchArray=[];
var categories=[];
	categories.push("alcohol");
	categories.push("beauty");
	categories.push("car");
	categories.push("finance");
	categories.push("food");
	categories.push("general");
	categories.push("medical");
	categories.push("retail");
	categories.push("technology");
	categories.push("tourism");
$(document).ready(function(){
	/*initSandals();
	var irwintick=1;
	$("#beercan").click(function(){
		document.getElementById("irwin"+irwintick).play();
		if(irwintick>=3) 
			irwintick=1;
		else
			irwintick++;
		
	});*/
	
	//need javascript resizing again
	$(window).bind("resize",windowResize);
	windowResize();
	$(".subMenu").data("visible","0");
	$(".menuButton").bind("click",toggleMenu);
	initReelArchive();
	//movie controls
	$("#blackout").bind("click",destroyMovie);
	$("#theatreClose").bind("click",destroyMovie);
	
	$(".searchButton").hover(function(){
		$(this).attr("src","img/search_iconb.png");
	},function(){
		$(this).attr("src","img/search_icon.png");
	});
	$(".cancelSearchButton").hover(function(){
		$(this).attr("src","img/cancel_search_iconb.png");
	},function(){
		$(this).attr("src","img/cancel_search_icon.png");
	});
	$("#newsCancel").click(function(){
		$(this).hide();
		setArchive("news",0,0);
		$("#newsSearchTerms").attr("value","");
	});
	$("#reelCancel").click(function(){
		$(this).hide();
		setArchive("reel",0,15);
		initReelArchive();
		$("#reelSearchTerms").attr("value","");
	});
	$("#reelCategory").data("searchType","category");
	$("#reelKeyword").data("searchType","keyword");
	$("#archiveCategory").data("searchType","category");
	$("#archiveKeyword").data("searchType","keyword");
	$("#newsArchiveSearchBox span").click(function(){
		$("#reelArchiveSearchBox").find("span").removeClass("black");
		$(this).addClass("black");
		//$("#newsSearchTerms").data("searchType",$(this).data("searchType"));
	});
	$("#reelArchiveSearchBox span").click(function(){
		$("#reelArchiveSearchBox").find("span").removeClass("black");
		$(this).addClass("black");
		$("#reelSearchTerms").remove();
		var rep=toggleSearchType("reel",$(this).data("searchType"));
		$("#reelArchiveSearchBox").append(rep);
	});
	//this plugin is your new god. worship it.
	$.history.init(function(hash){
        if(hash == "") {
            // initialize your app
        	$("#switchBox>div").hide();
        	$("#navSubtitle").html("");
        	$("#sliderTitleBox").fadeIn("fast");
        	$("#switch").fadeIn("fast");
        	try{
				if(hash=="splash"){
					clearTimeout(s_timer);
					s_timer=setTimeout(s_recursive,s_slideDelay);
				}else{
					s_timer=setTimeout(s_recursive,s_slideDelay);
				}
			}catch(e){
				s_timer=setTimeout(s_recursive,s_slideDelay);
				//attempt to start/stop the timer but it's a non-critical fail
				//it will self initialize after a mouseover+off
			}
        	oldPage=currentPage;
        } else {
            // restore the state from hash
        	$(".navClick").removeClass("selectedNav");
    		$(".menuButton").removeClass("selectedNav");
    		$(".subMenu").each(function(){
    			$(this).css({"bottom":"-250%"});
    			$(this).data("visible","0");
    		});
    		hash=hash.split("/");
    		currentPage=hash[0];
    		if(currentPage!="editorReel") $("#navTitle").html(pages[currentPage].title);
    		destroyMovie();
    		clearTimeout(s_timer);
    		$(".s_tb_container").each(function(){
				var flag=false;
    			var cont=$("#switch_"+$(this).data("id")+":visible");
				if($(this).data("xAxis")=="0"){
					cont.animate({
						"left":"0%"
					});
					cont.find(".articleTextBox").animate({
						"right":"-62%"
					});
				}else{
					cont.animate({
						"right":"0%"
					});
					cont.find(".articleTextBox").animate({	
						"left":"-62%"
					});
				}
				$(this).find(".s_tb_title").fadeIn("fast");
				//resume the slideshow
				//s_timer=setTimeout(s_recursive,s_slideDelay);
				$(this).find(".s_tb_icon").attr("src","img/iris_animate_close.gif");
				$(this).data("visible","0");
    		});
    		$("#switchBox>div").fadeOut("fast");
        	$("#"+pages[oldPage].div).fadeOut("fast",function(){
    			//slider container title boxes
    			$("#sliderTitleBox").fadeOut("fast");
    			switch(currentPage){
    				case "reels":
    					getRecentWork();
    					break;
    				case "newsArc":
    					setArchive("news",0,0);
    					break;
    				case "reelArc":
    					setArchive("reel",0,15);
    					break;
    				case "editorReel":
    					$("#navTitle").html(editors[hash[1]].name);
    					$("#navSubtitle").html(editors[hash[1]].position);
    					getEditorReel(hash[1],3);
    					break;
    				case "splash":
    					$("#sliderTitleBox").fadeIn("fast");
    					$("#navSubtitle").html("");
    					try{
    						if(hash=="splash")
    							s_timer=setTimeout(s_recursive,s_slideDelay);
    						else
    							clearTimeout(s_timer);
    					}catch(e){
    						//attempt to start/stop the timer but it's a non-critical fail
    						//it will self initialize after a mouseover+off
    					}
    					break;
    				case "contact":
    					$("#googleMapDiv").html("");
    					var geocoder;
    					var map;
    					var googleLoc;
    					function initMap() {
    						geocoder = new google.maps.Geocoder();
    					    geocoder.geocode( { 'address': "alter ego post production near 488 Wellington St W, Toronto, ON M5V, Canada"}, function(results, status) {
    					    	if (status == google.maps.GeocoderStatus.OK) {
    					    		var myOptions = {
    					    			zoom: 15,
    							    	mapTypeId: google.maps.MapTypeId.ROADMAP
    							    }
    							    map = new google.maps.Map(document.getElementById("googleMapDiv"), myOptions);
    					    		map.setCenter(results[0].geometry.location);
    					    		marker = new google.maps.Marker({
    					    			map: map, 
    					    			position: results[0].geometry.location,
    					    			icon:"http://media.alteregopost.com/images/google_map_icon.png"
    					    		});
    					      }else{
    					    	  alert("Geocode was not successful for the following reason: " + status);
    					      }
    					    });
    					  }
    					initMap();
    					break;
    				case "MVS":
    					getMusicVideos(0,15);
    					initReelArchive();
    					break;
    			}
    			$("#"+pages[hash[0]].div).fadeIn("fast");
    			oldPage=currentPage;
    		});
        }
    },
    { unescape: ",/" });
	
	//page changes using the pages array to add a layer of abstraction
	$(".navClick").click(function(e){
		var curr=$(this).attr("href");
		if(curr.indexOf("#editorReel")>=0){
			id=$(this).attr("id");
			currentPage=curr+"-"+id;
			$("#navTitle").html(editors[id].name);
			$("#navSubtitle").html(editors[id].position);
		}else{
			currentPage=curr;
			$("#navSubtitle").html("");
		}
		//reset reel submenus
		$(".reelMenuHead").each(function(){
			$(this).data("visible","0");
			$(this).css("color","#71757D");
			if($(this).siblings(".menuNames").hasClass("longNames")){
				$(this).siblings(".menuNames").animate({
					"right":"-400%"
				});
			}else{
				$(this).siblings(".menuNames").animate({
					"right":"-200%"
				});
			}
		});
		
		editorId=$(this).attr("id");
	});
	
	$(".reelMenuHead").data("visible","0");
	$(".reelMenuHead").click(function(){
		$(".reelMenuHead").each(function(){
			$(this).data("visible","0");
			$(this).css("color","#71757D");
			if($(this).siblings(".menuNames").hasClass("longNames")){
				$(this).siblings(".menuNames").animate({
					"right":"-400%"
				});
			}else{
				$(this).siblings(".menuNames").animate({
					"right":"-200%"
				});
			}
		});
		var thisTemp=$(this);
		setTimeout(function(){
			var curr=thisTemp;
			var vis=curr.data("visible");
			if(vis=="0"){
				curr.data("visible","1");
				curr.css("color","#AF1B4D");
				curr.siblings(".menuNames").show();
				curr.siblings(".menuNames").animate({
						"right":"105%"
				},MENU_CHANGE);
			}else{
				curr.data("visible","0");
				curr.css("color","#71757D");
				if(curr.siblings(".menuNames").hasClass("longNames")){
					curr.siblings(".menuNames").animate({
						"right":"-400%"
					},MENU_CHANGE);
				}else{
					curr.siblings(".menuNames").animate({
						"right":"-200%"
					},MENU_CHANGE);
				}
			}
		},MENU_CHANGE);
	});
	
	$(".stretch>div").hover(function(){
		$(this).find(".stretchImg").css("borderStyle","solid");
		$(this).find(".stretchImg").css("borderColor","#FFF");
		$(this).find(".stretchImg").css({
			"borderWidth":"3px",
			"left":"-3px",
			"bottom":"-3px"
		});
	},function(){
		$(this).find(".stretchImg").css({
			"borderWidth":"0px",
			"left":"0px",
			"bottom":"0px"
		});
	});
	
	$("#newsSearchTerms").data("type","news");
	$("#newsSearchTerms").keydown(function(event){
		if(event.keyCode==13) searchArchives("newsSearchTerms");
	});
	$("#newsSearch").data("type","news");
	$("#newsSearch").click(function(){
		searchArchives("newsSearchTerms");
	});
	$("#newsSearchTerms").focus(function(){
		if($(this).val()=="search..") $(this).val("");
	});
	
	$("#reelSearchTerms").data("type","reel");
	$("#reelSearchTerms").keydown(function(event){
		if(event.keyCode==13) searchArchives("reelSearchTerms");
	});
	$("#reelSearchTerms").focus(function(){
		if($(this).val()=="search..") $(this).val("");
	});
	$("#reelSearch").data("type","reel");
	$("#reelSearch").click(function(){
		searchArchives("reelSearchTerms");
	});
});

function searchArchives(org){
	var params=$("#"+org).val();
	var type=$("#"+org).data("type");
	var method=$("#"+org).data("searchType");
	if(!notNull(method)) method="keyword";
	params=params.replace(/[&]/g,"u0026");
	//$("#loadingBox").show();
	if(params=="flip me!"){
		var deg;
		if(flipped){
			deg=0; 
			flipped=false;
		}else{
			deg=180;
			flipped=true;
		}
		$("body").css({
			"transform": "rotate("+deg+"deg)",
			"-moz-transform": "rotate("+deg+"deg)",
			"-o-transform": "rotate("+deg+"deg)",
			"-webkit-transform": "rotate("+deg+"deg)"
		});
		return true;
	}
	$.ajax({
		url:"php/ajaxWrapper.php",
		type:"post",
		data:"type=searchArchive&searchType="+type+"&params="+params+"&method="+method,
		dataType:"json",
		success:function(data){
			if(type=="news"){
				$("#newsCancel").show();
				if(data.error){
					alert(data.error);
					return true;
				}
				$("#newsArchiveBox").remove();
				var temp=$("<div>",{"id":"newsArchiveBox"});
				$("#newsArchive .mark").append(temp);
				
				var article;
				$("#loadingBox").hide();
				for(var n in data){
					article="";
					try{
						var aPosition = data[n].article.indexOf("<br>");
						if(aPosition==-1) aPosition = data[n].article.indexOf("<br/>");
						if(aPosition!=-1){
							var secondPos = data[n].article.indexOf("<br>", aPosition + 1);
							if(secondPos==-1) secondPos = data[n].article.indexOf("<br/>", aPosition + 1);
						}
						var cutoff= (notNull(secondPos) && secondPos!=-1)? secondPos: 100;
						if(data[n].article.length>103){
							article=data[n].article.substr(0,cutoff);
							article=article+"...";
						}
					}catch(e){/*index out of bound exception I don't care about*/}
					
					var parsedDate=parseDate(data[n].creation_date);
					var toss=createNode(data[n].id,data[n].thumbnail,data[n].title,article,parsedDate);
					$("#newsArchiveBox").append(toss);
				}
				$("#newsArchiveBox").jScrollPane({
					showArrows:true
				});
				var api=$("#newsArchiveBox").data("jsp");
				api.reinitialise({
					showArrows: true
				});
			}else{
				searchArray=[];
				//cache the search result
				for(var t in data){
					searchArray.push(data[t]);
				}
				$("#reelCancel").show();
				$("#reelArchiveBox").html("");
				var pass=[];
				//display the first 15 results
				var temp= (searchArray.length>15)? 15: parseInt(searchArray.length);
				for(var k=0;k<temp;k++){	
					pass.push(data[k]);
				}
				ret=createReelBlock(pass);
				$("#reelArchiveBox").append(ret);
				//set the page indicators to control the spot archive for search results
				$("#reelArchiveControlsBox").html("");
				var len=parseInt(searchArray.length/15);
				if(searchArray.length%15) len++;
				for(var i=0;i<len;i++){
					var img=$("<span>",{
						"id":"ar_switch_control_"+i
					}).html((i+1)).addClass("sliderButton").data("page",i).bind("click",function(){
						var page=$(this).data("page");
						ar_new=page;
						$("#reelArchiveControlsBox span").removeClass("selected").css("color","#71757D");
						$(this).addClass("selected");
						$(this).css("color","#555");
						
						$("#reelArchiveControlsBox img").each(function(k,item){
							$(this).attr("src","img/slide_dot_off.png");
						});
						
						$("#reelArchiveBox").fadeOut("fast",function(){
							var cache=parseInt(page);
							var pass=[];
							//display the first 15 results
							for(var k=(cache*15);k<((cache+1)*15);k++){	
								try{	
									if(notNull(searchArray[k]))	pass.push(searchArray[k]);
								}catch(e){break;}
							}
							ret=createReelBlock(pass);
							$("#reelArchiveBox").html("");
							$("#reelArchiveBox").append(ret);
							windowResize();
							$("#reelArchiveBox").fadeIn("fast");
							$("#ar_switch_control_"+ar_new).attr("src","img/slide_dot_on.png");
						});
					});
					if(i==0) img.css("color","#555");
					$("#reelArchiveControlsBox").append(img);
				}
			}
			windowResize();
		},
		error:function(e){
			alert("Searching error "+e.responseText);
		}
	});
}

function windowResize(e){
	/* In all honesty, it's not THAT bad of a monster. The stitching is nice, right?
	 * This script also corrects a FF bug where it doesn't resize the image properly and does some weird math. IE and safari have no problem
	 */
	var myWidth=0, myHeight=0, newWidth=0, newHeight=0;
	var dims=windowDims();
	myWidth=dims['width'];
	myHeight=dims['height'];
	
	//for the snow catching
	/*WINDOW_WIDTH=myWidth;
	WINDOW_HEIGHT=myHeight;
	$("#snowbox").attr({
		"width":WINDOW_WIDTH+"px",
		"height":WINDOW_HEIGHT+"px"
	});*/
	
	//the following calculates the sizing of the container 
	newWidth=parseInt((myHeight*1.778*RESIZE_PERCENT)*.75);//.81 is the height of the container, 1.778 is 16:9 aspect and .75 is the width
	$("#cardTitleBox").css("width",newWidth+"px");
	$("#container").css("width",newWidth+"px");
	//the showreels layout grid has it's own unique aspect ratio (3.03)
	gridHeight=parseInt(newWidth/3.03);
	gridHeight= (gridHeight<MIN_GRID_HEIGHT)? MIN_GRID_HEIGHT: gridHeight;
	$(".grid").css("height",gridHeight+"px");

	//1245px = 90%
	//815px = 70%
	//gives a ratio of 1%/21.5px
	newFont=parseInt((newWidth-815)/21.5);
	newFont= (newFont<0)? MIN_FONT: MIN_FONT+newFont;
	$("body").css("font-size",parseInt(newFont)+"%");
	
	
	newHeight=parseInt(newWidth/1.778);
	if(myWidth/myHeight<1.778){
		newHeight=(myWidth/1.778*RESIZE_PERCENT)*.81; //.81 is the height of the container, 1.778 is 16:9 aspect and .75 is the width
		
		$("#container").css("width",parseInt(newHeight*1.778)+"px");
		$("#cardTitleBox").css("width",parseInt(newHeight*1.778)+"px");
		newWidth=parseInt(newHeight*1.778);
		//the showreels layout grid has it's own unique aspect ratio (3.03)
		gridHeight=parseInt(newHeight/3.03*1.778);
		gridHeight= (gridHeight<MIN_GRID_HEIGHT)? MIN_GRID_HEIGHT: gridHeight;
		$(".grid").css("height",gridHeight+"px");
		
		newFont=parseInt((newHeight-458)/21.5);
		newFont= (newFont<0)? MIN_FONT: MIN_FONT+newFont;
		$("body").css("font-size",parseInt(newFont)+"%");
	}
	reelHeight=parseInt(newWidth/2.098);
	//if(reelHeight<380) reelHeight=380;
	$("#switchBox").css("height",reelHeight+"px");
	//vertical offset
	//magic int's woot! no really, 75 just fixes it. no idea...
	newTop=parseInt(((myHeight/2)-(newHeight/2)-50)/2);///myHeight*100)/2;
	$("#internalBox").css("top",newTop+"px");
	newLeft=parseInt((myWidth*.81*RESIZE_PERCENT/2)-(newWidth/2*RESIZE_PERCENT));
	
	//more snow stuff
	/*COLLECT_WIDTH=newWidth;
	COLLECT_HEIGHT=newHeight+2;
	COLLECT_TOP=newTop;*/
	
	$(".articleTextBody").each(function(){
	try{
		var api=$(this).data("jsp");
		api.reinitialise({
			showArrows: true
		});
		}catch(e){/*IE killer*/}
	});
	try{
		var api=$("#newsArchiveBox").data("jsp");
		api.reinitialise({
			showArrows: true
		});
	}catch(e){/*IE killer*/}
}

/** Apart from returning the window dimensions in an object it also set the iphone global
 */
function windowDims(){
	var myWidth;
	var myHeight;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;	
	}else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	}else if(typeof(document.body.offsetWidth)=='number'){
		myWidth=document.body.offsetWidth;
		myHeight=document.body.offsetHeight;
	}
	//need to add an absolute scalin g factor
	return ({"width":myWidth,"height":(myHeight)});
}

function notNull(str){
	if(str=="undefined" || str=="" || str==null || str==false || str=="null")
		return false;
	else
		return true;
}

function getRecentWork(){
	$.ajax({
		url:"php/ajaxWrapper.php",
		type:"post",
		data:"type=recentWork",
		dataType:"json",
		success:function(data){
			var temp=createReelBlock(data);
			$("#showreels").html("");
			$("#showreels").append(temp);
			windowResize();
		},
		error:function(data){
			alert(data.responseText);
		}
	});
}

function getMusicVideos(page,size){
	$.ajax({
		url:"php/ajaxWrapper.php",
		type:"post",
		data:"type=getMusicVideos&page="+page+"&size="+size,
		dataType:"json",
		success:function(data){
			if(notNull(data.error)){
				alert(data.error);
				return true;
			}
			$("#musicVideosBox").html("");
			ret=createReelBlock(data);
			$("#musicVideosBox").append(ret);
			windowResize();
		},
		error:function(data){
			alert(data.responseText);
		}
	});
}

/**performs the ajax request and dom creation for the news archive
*/
function setArchive(arc,page,size){
	//$("#loadingBox").show();
	$.ajax({
		url:"php/ajaxWrapper.php",
		type:"post",
		data:"type=getArchive&arcType="+arc+"&page="+page+"&size="+size,
		dataType:"json",
		success:function(data){
			if(notNull(data.error)){
				alert(data.error);
				return true;
			}
			
			if(arc=="news"){
				if(data.error){
					alert(data.error);
					return true;
				}
				$("#newsArchiveBox").remove();
				var temp=$("<div>",{"id":"newsArchiveBox"});

				var article;
				$("#loadingBox").hide();
				for(var n in data){
					article="";
					try{
						var aPosition = data[n].article.indexOf("<br>");
						if(aPosition==-1) aPosition = data[n].article.indexOf("<br/>");
						if(aPosition!=-1){
							var secondPos = data[n].article.indexOf("<br>", aPosition + 1);
							if(secondPos==-1) secondPos = data[n].article.indexOf("<br/>", aPosition + 1);
						}
						var cutoff= (notNull(secondPos) && secondPos!=-1)? secondPos: 100;
						if(data[n].article.length>103){
							article=data[n].article.substr(0,cutoff);
							article=article+"...";
						}
					}catch(e){/*index out of bound exception I don't care about*/}
					
					var parsedDate=parseDate(data[n].creation_date);
					var toss=createNode(data[n].id,data[n].thumbnail,data[n].title,article,parsedDate);
					temp.append(toss);
				}
				$("#newsArchive .mark").append(temp);
				setTimeout(function(){
					$("#newsArchiveBox").jScrollPane({
						showArrows:true
					});
					var api=$("#newsArchiveBox").data("jsp");
					api.reinitialise({
						showArrows: true
					});
				},500);
			}else{
				$("#reelArchiveBox").html("");
				ret=createReelBlock(data);
				$("#reelArchiveBox").append(ret);
			}
			windowResize();
		},
		error:function(data){
			alert(data.responseText);
		}
	});
}
function createNode(id,img,title,body,date){
	var div=$("<div>").addClass("archiveNodeBox");
	div.data("id",id);
	div.click(function(){
		var id=$(this).data("id");
		$.ajax({
			async:"false",
			url:"php/ajaxWrapper.php",
			type:"post",
			data:"type=getArchivedNews&id="+id,
			dataType:"json",
			success:function(data){
				if(notNull(data.error)){
					alert(data.error);
					return true;
				}
				$("#loadingBox").show();
				clickEvent(data);
			},
			error:function(data){
				
			}
		});
		
		function clickEvent(data){
			$("#newsArchiveSingle").html("");
			//var arrid=s_images.length;
			var news=data[0]['news'];
			var arrid=news.id;
			s_images[news.id]=news;
			//create the card
			var div=$("<div>",{
				"id":"arc_switch_"+news.id
			}).addClass("cardBox");
			div.css("color",news.c_text_colour);
			
			//create the card image
			var back=$("<img></img>",{
				src:"uploads/"+s_images[arrid].big_pic
			}).addClass("cardImage");
			var mediaArr=[];
				if(notNull(data[0]["m1"])) mediaArr.push(data[0]["m1"]);
				if(notNull(data[0]["m2"])) mediaArr.push(data[0]["m2"]);
				if(notNull(data[0]["m3"])) mediaArr.push(data[0]["m3"]); 
	        s_media[news.id]=mediaArr;
			//create the text blocks
			var titleBox=createArticleTitle(arrid,true);
			var textBox=createFullArticle(news.id);
			if(titleBox.data("xAxis")=="0"){
				textBox.css("right","-44%");
				titleBox.css({
					"left":"49%",
					"display":"block"
				});
				div.css("left","100%");
			}else{
				textBox.css("left","-44%");
				titleBox.css({
					"right":"49%",
					"display":"block"
				});
				div.css("left","-100%");
			}
			
			titleBox.click(function(){
				$("#navTitle").fadeIn(ARC_SLIDE_DELAY);
				$("#loadingBox").hide();
				if($(this).data("xAxis")=="0"){
					$("#newsArchive .mark").animate({
						"left":"0%"
					},ARC_SLIDE_DELAY-400);
					$("#newsArchiveSingle").animate({
						"left":"100%"
					},ARC_SLIDE_DELAY,function(){
						$(this).css("left","0%");
					});
				}else{
					$("#newsArchive .mark").animate({
						"left":"0%"
					},ARC_SLIDE_DELAY-400);
					$("#newsArchiveSingle").animate({
						"left":"-100%"
					},ARC_SLIDE_DELAY,function(){
						$(this).css("left","0%");
					});
				}
			});
			
			div.append(titleBox);
			div.append(textBox);
			div.append(back);
			$("#newsArchiveSingle").append(div);
			$("#loadingBox").show();
			try{
				$(".articleTextBody").jScrollPane({
					showArrows: true
				});
			}catch(e){/*IE killer*/}
			$("#navTitle").fadeOut(ARC_SLIDE_DELAY);
			if(titleBox.data("xAxis")=="0"){
				$("#newsArchive .mark").animate({
					"left":"-143%"
				},ARC_SLIDE_DELAY+100);
				$("#newsArchiveSingle").animate({
					"left":"-143%"
				},ARC_SLIDE_DELAY);
				$("#loadingBox").fadeOut(ARC_SLIDE_DELAY);
			}else{
				$("#newsArchive .mark").animate({
					"left":"144%"
				},ARC_SLIDE_DELAY+100);
				$("#newsArchiveSingle").animate({
					"left":"144%"
				},ARC_SLIDE_DELAY);
				$("#loadingBox").fadeOut(ARC_SLIDE_DELAY);
			}
		}
	});
	var domImg=$("<img/>",{
		src:"uploads/"+img
	}).addClass("archiveNodeImg");
	var conDiv=$("<div>").addClass("archiveNodeTextBox");
		var title=$("<p>").addClass("archiveNodeTitle").html(title);
		var bodyt=$("<p>").addClass("archiveNodeBody").html(body);
		var date=$("<div>").addClass("archiveNodeDate").html(date);

	conDiv.append(title);
	conDiv.append(date);
	conDiv.append(bodyt);
	div.append(domImg);
	div.append(conDiv);
	return div;
}

function toggleSearchType(area,type){
	var ret;
	switch(area){
		case "reel":
		case "news":
			ret="";
			break;
		default:
			return false;
	}
	if(type=="keyword"){
		//<input id="newsSearchTerms" type="text" name="searchTerms" style="width:100%"/>
		ret=$("<input>",{type:"text",name:"searchTerms",id:area+"SearchTerms"});
		ret.css("width","100%");
	}else{
		ret=$("<select>",{name:"searchTerms",id:area+"SearchTerms"});
		ret.css("width","100%");
		for(var c in categories){
			var opt=$("<option>",{value:categories[c],name:"searchTerms",id:area+"SearchTerms"}).html(categories[c]);
			opt.css("width","100%");
			ret.append(opt);
		}
	}
	ret.data("searchType",type);
	ret.data("type",area);
	ret.keydown(function(event){
		var ar=area;
		if(event.keyCode==13) searchArchives(ar+"SearchTerms");
	});
	return ret;
}

function toggleMenu(){
	$(".navClick").removeClass("selectedNav");
	$(".menuButton").removeClass("selectedNav");
	$(this).addClass("selectedNav");
	
	var targ=$(this).siblings(".subMenu");
	if(targ.data("visible")=="0"){
		$(".subMenu").data("visible","0");
		$(".subMenu[class!=selectedNav]").animate({"bottom":"-250%"},MENU_CHANGE);
		targ.animate({"bottom":"100%"},MENU_CHANGE);
		targ.data("visible","1");
	}else{
		//reset reel submenus
		targ.animate({"bottom":"-250%"},MENU_CHANGE);
		targ.data("visible","0");
	}
	$(".reelMenuHead").each(function(){
		$(this).data("visible","0");
		$(this).css("color","#71757D");
		if($(this).siblings(".menuNames").hasClass("longNames")){
			$(this).siblings(".menuNames").animate({"right":"-400%"},MENU_CHANGE);
		}else{
			$(this).siblings(".menuNames").animate({"right":"-200%"},MENU_CHANGE);
		}
	});
}

function createReelBlock(data,mag){
	if(!mag) mag=5;
	var grid=$("<div>").addClass("grid");
	if(data.length==0) grid.html("coming soon");
	
	var row;
	var len=parseInt(data.length/mag);
	if(data.length%mag) len++;
	for(i=0;i<len;i++){
		row=$("<div>").addClass("row");
		//need to add an exception for anything for mag < 5
		if(mag==3) row.css("left","21%");
		
		for(k=(i*mag);k<((i+1)*mag);k++){
			//do not exceed data length
			if(k>=data.length) break;
			var stretch=$("<div>").addClass("stretch");
			var sc=$("<div>").addClass("stretchContent");
				sc.data("id",data[k].id);
			var img=$("<img></img>",{src:"uploads/"+data[k].thumbnail}).addClass("stretchImg");
			
			sc.bind("click",createMovie);
			sc.hover(function(){
				$(this).find(".stretchImg").css("borderStyle","solid");
				$(this).find(".stretchImg").css("borderColor","#FFF");
				$(this).find(".stretchImg").css({
					"borderWidth":"3px",
					"left":"-3px",
					"bottom":"-3px"
				});
			},function(){
				$(this).find(".stretchImg").css({
					"borderWidth":"0px",
					"left":"0px",
					"bottom":"0px"
				});
			});
			var st=$("<div>").addClass("stretchText");
				var div=$("<div>").html(data[k].company+"<br>"+data[k].title);
			st.append(div);
			
			sc.append(img);
			sc.append(st);
			stretch.append(sc);
			row.append(stretch);
		}
		grid.append(row);
	}	
	return grid;
}
/** create the page numbers for archive and search results > 15
 * type<str> switch between archive ("archive") and search ("search") results
 */
function initReelArchive(){
	$.ajax({
		url:"php/ajaxWrapper.php",
		type:"post",
		data:"type=getLengths",
		dataType:"json",
		success:function(data){
			if(notNull(data.error)){
				alert(data.error);
				return true;
			}
			$("#reelArchiveControlsBox").html("");
			var len=Math.round(data[0].arc_count/15);
			if(data[0].arc_count%15) len++;
			for(var i=0;i<(len-1);i++){
				var source= (i==0)? "img/slide_dot_on.png": "img/slide_dot_off.png";
				var img=$("<span>",{
					"id":"ar_switch_control_"+i
				}).html((i+1)).addClass("sliderButton").data("page",i);
				
				img.click(changeReelPage);
				if(i==0) img.css("color","#555");
				$("#reelArchiveControlsBox").append(img);
			}
			
			$("#musicVideosControlsBox").html("");
			len=parseInt(data[1].mv_count/15);
			if(data[1].mv_count%15) len++;
			for(var i=0;i<(len-1);i++){
				var source= (i==0)? "img/slide_dot_on.png": "img/slide_dot_off.png";
				var img=$("<span>",{
					"id":"ar_switch_control_"+i
				}).html((i+1)).addClass("sliderButton").data("page",i);
				
				img.click(changeMVPage);
				if(i==0) img.css("color","#555");
				$("#musicVideosControlsBox").append(img);
			}
		},error:function(data){
			//alert(data.responseText);
		}
	});
}

		function changeReelPage(){
			var page=$(this).data("page");
			ar_new=page;
			$("#reelArchiveControlsBox span").removeClass("selected").css("color","#71757D");
			$(this).addClass("selected");
			$(this).css("color","#555");
			
			$("#reelArchiveControlsBox img").each(function(k,item){
				$(this).attr("src","img/slide_dot_off.png");
			});
			
			$("#reelArchiveBox").fadeOut("fast",function(){
				var cache=page;
				setArchive("reel",cache,15);
				$("#reelArchiveBox").fadeIn("fast");
				$("#ar_switch_control_"+ar_new).attr("src","img/slide_dot_on.png");
			});
		}
		
		function changeMVPage(){
			var page=$(this).data("page");
			ar_new=page;
			$("#musicVideosControlsBox span").removeClass("selected").css("color","#71757D");
			$(this).addClass("selected");
			$(this).css("color","#555");
			
			$("#musicVideosControlsBox img").each(function(k,item){
				$(this).attr("src","img/slide_dot_off.png");
			});
			
			$("#musicVideosBox").fadeOut("fast",function(){
				var cache=page;
				getMusicVideos(cache,15);
				$("#musicVideosBox").fadeIn("fast");
				$("#ar_switch_control_"+ar_new).attr("src","img/slide_dot_on.png");
			});
		}

function getEditorReel(rid){
	$.ajax({
		url:"php/ajaxWrapper.php",
		type:"post",
		data:"type=getEditorReel&rid="+rid,
		dataType:"json",
		success:function(data){
			if(notNull(data.error)){
				alert(data.error);
				return true;
			}
			var ret=createReelBlock(data,3);
			$("#reelsBox").html("");
			$("#reelsBox").fadeIn("fast");
			$("#reelsBox").append(ret);
			windowResize();
		},
		error:function(data){
			alert(data.responseText);
		}
	});
}

function createMovie(){
	var id=$(this).data("id");
	//snowTimer=false;
	$.ajax({
		url:"php/ajaxWrapper.php",
		type:"get",
		data:"param="+id,
		dataType:"json",
		success:function(data){
			if(notNull(data.error)){
				alert("error: "+data.error);
				return true;
			}
			$("#movieInfo").css("right","0px");
			$("#lightbox").fadeIn("fast",function(){
				var src=data.src;
				var width=data.width;
				var height=data.height;
				var htmlHeight=parseInt(height)+35;
				$("#theatre").animate({
					"height":height+"px",
					"marginTop":"-"+parseInt(htmlHeight/2)+"px",
					"width":width+"px",
					"marginLeft":"-"+parseInt(width/2)+"px"
				},function(){
					//the duplicated flash html is for FF since it won't treat the object as an alternate source
					//left it in place for IE and anything that can't use h.264 but can use flash
					var qtHeight=parseInt(height)+18;
					var vid=$("#screen").find("video");
					vid.attr("width",width);
					vid.attr("height",height);
					qt=QT_GenerateOBJECTText("uploads/"+src, width, qtHeight, '', 'AUTOPLAY', 'true','EnableJavaScript', 'true',
							 'postdomevents', 'true','emb#NAME','movie2', 'obj#id', 'movie2', 'BGCOLOR', '000000');
					//anything that does have <video> support
					if($("html").hasClass("no-video") || getIEVersionNumber() || /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
						$("#screen").html("<div id='flashScreen'></div>");
						swfobject.embedSWF("flash/videoPlayer.swf","flashScreen",width,parseInt(height)+50,"9","",{
							"sourceUrl":"http://www.alteregopost.com/uploads/"+src,
							"stagew":width,
							"stageh":height
						},{
							bgcolor:"#000",
							play:"true",
							loop:"false",
							wmode:"transparent",
							allowFullScreen:"true",
							allowScriptAccess:"sameDomain"							
						},{
							align:"top"
						});
					}else{
						vid.html('<source src="uploads/'+src+'" type="video/mp4" onerror="vidSrcError()"></source>').error(function(){});
					}
					$("#movieInfo").html(data.company+"<br/>"+data.title+"<br/><div class='description'>"+data.description+"</div>");
					$("#movieInfo").animate({
						"right":"-225px"
					},1000);
				});
			});
		},
		error:function(data){
			alert("server error: "+data.responseText);
		}
	});
}
function vidSrcError(){
	//FF4
	var vid=$("#screen").find("video");
	vid.html("");
	vid.append(qt);
}

function destroyMovie(){
	if($("html").hasClass("no-video")  || getIEVersionNumber()){
		$("#screen").html("");	
	}else{
		$("#screen").html("<video width='640' height='480' controls autoplay>");
		$("#screen").css("height","0px");
	}
	$("#movieInfo").html("");
	$("#movieInfo").css("top","0px");
	$("#lightbox").fadeOut("slow",function(){
		$("#screen").css("height","100%");
	});
	//snowTimer=true;
}

function parseDate(date){
	//date is expected in yyyy-mm-dd hh:mm:ss format
	var str="";
	var parts=date.split("-");
	str=str+months[parts[1]]+" ";
	str+=parts[0];
	return str;
}

function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}
