// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);;
var cur_issue = 1;
//var homedir = "http://www.filmonair.com/"; OLD
var gs1 = "http://www.filmoa.com/";
var gs2 = "http://www.foair.com/";
var userid;
var iOS = 0;
if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') { iOS = 1; };

jQuery(document).ready(function () {

	// WINDOW RESIZE //
	var blabla = 0;
	if(blabla == 1) {
	// MOVE TO MAG???????????
	jQuery("#mag_content").css({"-webkit-transform-origin": "0 0", "-webkit-transform" : "scale(0.85)", "-webkit-transition-timing-function" : "ease-out", "-webkit-transition-duration" : "400ms"});
	jQuery("#bignextfixed").css({"-webkit-transform-origin": "0 0", "-webkit-transform" : "scale(0.85)", "-webkit-transition-timing-function" : "ease-out", "-webkit-transition-duration" : "400ms"});
	jQuery("#pagebreak_blok").css({"-webkit-transform-origin": "0 0", "-webkit-transform" : "scale(0.85)", "-webkit-transition-timing-function" : "ease-out", "-webkit-transition-duration" : "400ms"});

	jQuery("#mag_content").css({"-moz-transform-origin": "0 0", "-moz-transform" : "scale(0.85)"});
	jQuery("#bignextfixed").css({"-moz-transform-origin": "0 0", "-moz-transform" : "scale(0.85)"});
	jQuery("#pagebreak_blok").css({"-moz-transform-origin": "0 0", "-moz-transform" : "scale(0.85)"});
	
	jQuery("#mag_content").css({msTransformOrigin: "0 0", msTransform : "scale(0.85)"});
	jQuery("#bignextfixed").css({msTransformOrigin: "0 0", msTransform : "scale(0.85)"});
	jQuery("#pagebreak_blok").css({msTransformOrigin: "0 0", msTransform : "scale(0.85)"});
	
	//-o-transform: rotate(360deg) scale(2);
	
	jQuery("#pagemiddle").css({left: (1004*0.85)+"px"});
	jQuery("#table_main").css({width: (jQuery("#table_main").width()*0.85)+"px", height: (jQuery("#table_main").height()*0.85)+"px"});
	jQuery(".gas0").css({left: (((1024*0.85)-768)/2)+"px"});

	}
	
	goRes(); jQuery(window).bind('resize', function() { goRes() });
	
	function goRes () {
		if(jQuery('.gallerybox').length == 1) {	
			var imghei = Math.round((galimghei/1920)*jQuery(window).width());	
			var imgmar = Math.round((jQuery(window).height()-imghei)/2);
			jQuery(".gallerybox .galimg").css({ height: imghei+"px", width: jQuery(window).width()+"px", marginTop: imgmar+"px" });			
			if(iOS == 1) {
				imghei = Math.round((galimghei/1920)*window.innerWidth);
				jQuery(".gallerybox").css({ position: "absolute", top: window.scrollY, width: window.innerWidth, height: window.innerHeight }); 
				jQuery(".gallerybox .galimg").css({ height: imghei+"px", width: window.innerWidth+"px", marginTop: imgmar+"px" });
			};
		}
	};
	
	
	//	HEADER //
	
	var topbaropen = 1;
	jQuery('.topbarup').live('click', function(event) { // GO UP
		jQuery("#topbar20").animate({ marginTop: "-34px" }, 500);
		jQuery("#bignextfixed .bignextpage").animate({ top: "0px" }, 500);
		jQuery("#mag_main").animate({ marginTop: "0px" }, 500);
		jQuery(".topbarup").replaceWith("<a href=\"\" class=\"topbardown\"></a>");
		topbaropen = 0;	return false;
	});
	
	jQuery('.topbardown').live('click', function(event) { // APPEAR DOWN
		jQuery("#topbar20").animate({ marginTop: "0px" }, 500);
		jQuery("#bignextfixed .bignextpage").animate({ top: "34px" }, 500);
		jQuery("#mag_main").animate({ marginTop: "34px" }, 500);
		jQuery(".topbardown").replaceWith("<a href=\"\" class=\"topbarup\"></a>");
		topbaropen = 1;	return false;
	});
	
	
	// HEADER BOXES //
	
	var subscribeopen = 0; var socialopen = 0; var emailopen = 0; var adminopen = 0;
	
	jQuery(".newsubscribe").click(function() {
		if(subscribeopen == 0) {	closeBox(); topBoxShow("716", ".subscrbox2"); subscribeopen = 1;
		} else {					closeBox();
		} return false;
	});
	
	jQuery(".twitbirdbut, .twitbut, .facelike").click(function() {
		if(jQuery(".socialtopbox").html() == "") { 
			jQuery(".socialtopbox").html("<a href=\"http://twitter.com/filmonair\" class=\"twitter-follow-button\">Follow @filmonair</a><script src=\"http://platform.twitter.com/widgets.js\" type=\"text/javascript\"></script><br /><br /><iframe src=\"http://www.facebook.com/plugins/like.php?app_id=134306699726&amp;href=http%3A%2F%2Fwww.facebook.com%2Ffilmonair&amp;send=false&amp;layout=standard&amp;width=450&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font=tahoma&amp;height=80\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:200px; height:100px;\" allowTransparency=\"true\"></iframe>");
		}
	
		if(socialopen == 0) {		closeBox(); topBoxShow("537", ".socialtopbox");	socialopen = 1;
		} else {					closeBox();
		} return false;
	});	
	
	jQuery(".emailbut").click(function() {
		if(emailopen == 0) {		closeBox(); topBoxShow("742", ".emailtopbox");	emailopen = 1;
		} else {					closeBox();
		} return false;
	});
	
	jQuery(".adminbut").click(function() {
		if(adminopen == 0) {		closeBox(); topBoxShow("537", ".admintopbox");	adminopen = 1;
		} else {					closeBox();
		} return false;
	});
			
	// CLOSE BOXES //
	function closeBox(){
		if(subscribeopen == 1) {
			topBoxHide(".subscrbox2"); subscribeopen = 0;
		}
		if(socialopen == 1) {
			topBoxHide(".socialtopbox"); socialopen = 0;
		}
		if(emailopen == 1) {
			topBoxHide(".emailtopbox"); emailopen = 0;
		}
		if(adminopen == 1) {
			topBoxHide(".admintopbox"); adminopen = 0;
		}		
	}
	
	function topBoxShow (leftvar, idvar) {
		jQuery(idvar).appendTo("body");
		jQuery(idvar).css({ position: "fixed", marginLeft: 0, marginTop: 0, top: "9px", left: leftvar+"px", zIndex: "99999" });
		jQuery(idvar).animate({ marginTop: "25px", opacity: "toggle" }, 200);	
	}	
	function topBoxHide (idvar) {		jQuery(idvar).animate({ marginTop: "0px", opacity: "toggle" }, 200);		}
	
	// PLAY VID

	jQuery('.play').live('click', function(event) {
		clicky.log(this.href, 'Play Video'); // CLICKY
		
		cfl=0;
		if(jQuery(this).attr("class").indexOf("cfl") != -1) { cfl=1; }
		var id = jQuery(this).parent().attr("id");
		playVid(id);
		mainMute = 0;	
		return false;
	});
	
	
	// VID QUAL
	
	jQuery(".vidqual").live('mouseenter mouseleave', function(event) {
		if (event.type == 'mouseenter') {
			jQuery(this).animate({ opacity: 1 }, 200);
		} else {
			jQuery(this).animate({ opacity: 0.5 }, 200);
			if(vidqualopen == 1) {
				jQuery('.vidqual').animate({ height: "17px" }, 150);
				vidqualopen = 0;
				if (vidqual == 'hd') {	jQuery('.vidqual ul').animate({ marginTop: "-17px" }, 150);	}
			}
		}
	});
	
	var vidqualopen = 0;
	jQuery('.vidqual .more').live('click', function(event) {
		if(vidqualopen == 0) {
			jQuery('.vidqual').animate({ height: "34px" }, 150);
			vidqualopen = 1;
			jQuery('.vidqual ul').animate({ marginTop: "0px" }, 150);
		} else {
			jQuery('.vidqual').animate({ height: "17px" }, 150);
			vidqualopen = 0;
			if (vidqual == 'hd') {	jQuery('.vidqual ul').animate({ marginTop: "-17px" }, 150);	}
		}
		return false;
	});
	
	jQuery('.vidqual ul li a').live('click', function(event) {
		var curvidqual = vidqual;
		jQuery('.vidqual ul li a').removeClass('selected');
		jQuery(this).addClass('selected');
		vidqual = jQuery(this).text().toLowerCase();
		
		clicky.log(this.href, 'Change Video Quality '+vidqual); // CLICKY
		if((curvidqual != vidqual) && (nowplaying != 'ad')) {
			playVid(jQuery(".main_video li").first().attr("id"));
		}
		return false;
	});
	
	
	// HOOVER BIG NEXT PAGE
	
	jQuery(".bignextpage").live('mouseenter mouseleave', function(event) {
		if (event.type == 'mouseenter') {
			jQuery(".bignextpage a").animate({ opacity: 0.25 }, 150);
		} else {
			jQuery(".bignextpage a").animate({ opacity: 0.15 }, 150);
		}
	});	


	// DYNAMIC BOX NEXT/PREV //
	
	jQuery('.dynnext').live('click', function(event) {
		var thid = jQuery(this).attr("id");	thid = thid.replace("next","");
		var thwidth = jQuery(".dyn"+thid).width()*-1;
		var thwidthmove = thwidth;
		if(thid == "con") {		thwidthmove = thwidth + 244;	}
		
		jQuery("#prev"+thid).animate({ opacity: 1 }, 350);
		if(jQuery(".dyn"+thid+" .dyninbox").width() > (jQuery(".dyn"+thid+" .dyninbox").position().left*-1)-thwidth) {
			jQuery(".dyn"+thid+" .dyninbox").animate({ left: "+="+thwidthmove+"px" }, 350);
		} 
		if(jQuery(".dyn"+thid+" .dyninbox").width() <= (jQuery(".dyn"+thid+" .dyninbox").position().left*-1)-(thwidth*2)) {
			jQuery("#next"+thid).animate({ opacity: 0.25 }, 350);
		}		
		return false;
	});
	
	jQuery('.dynprev').live('click', function(event) {
		var thid = jQuery(this).attr("id");	thid = thid.replace("prev","");
		var thwidth = jQuery(".dyn"+thid).width();
		if(thid == "con") {		thwidth = thwidth - 244;	}

		jQuery("#next"+thid).animate({ opacity: 1 }, 350);
		if((jQuery(".dyn"+thid+" .dyninbox").position().left) < 0) {
			jQuery(".dyn"+thid+" .dyninbox").animate({ left: "+="+thwidth+"px" }, 350);
		} 
		if(((jQuery(".dyn"+thid+" .dyninbox").position().left)+thwidth) == 0) {
			jQuery("#prev"+thid).animate({ opacity: 0 }, 350);
		}		
		return false;
	});	
	
	
	
	jQuery('.dynper ul li').live('mouseenter mouseleave', function(event) {
		if (event.type == 'mouseenter') {
			jQuery(".link", this).animate({ opacity: 1 }, 150);		jQuery("img", this).animate({ opacity: .4 }, 150);
		} else {
			jQuery(".link", this).animate({ opacity: 0 }, 150);		jQuery("img", this).animate({ opacity: 1 }, 150);
		}
		return false;
	});		
	
	
	// CLOSE COMMENTS //
	
	jQuery('.commentx').live('click', function(event) {
		jQuery("#comment_box").animate({ opacity: 0 }, 350, function() { 
			jQuery("#comment_box").hide();
			jQuery("#vid_body p").css({ height: "546px", 'overflow': "hidden" });
		});
		return false;
	});
	
	
	// SOCIAL //
	
	jQuery(".soclbox").live('mouseenter mouseleave', function(event) {
		if (event.type == 'mouseenter') {
			if(jQuery(this).find(".socurl").length) {
				var href = jQuery(this).find(".socurl").attr("href");
				var link = jQuery(this).find(".socurl").text();
				jQuery(this).replaceWith( genSocial(href, link) );
			}
			jQuery(".pgbrk_share4, .pgbrk_share5, .pgbrk_share6").animate({ opacity: 1 }, 200);
		} else {	
			jQuery(".pgbrk_share4, .pgbrk_share5, .pgbrk_share6").animate({ opacity: 0 }, 200);
		}
	});
	
	
	// SEARCH //
	
	var searchopen = 0;
	jQuery('.insearchbut, .searchback').live('click', function(event) {
		if(searchopen == 0) {
			clicky.log(this.href, 'Open Search'); // CLICKY
			
			closeOverlay();
			jQuery('html, body').animate({scrollTop: "0px" }, 0);
			jQuery(".searchscreen").css({ height: jQuery(document).height()+"px", opacity: 1 });
			jQuery(".searchscreen").show();
			setTimeout(function(){ jQuery(".searchscreen").addClass('tdbackflip'); }, 50);
			searchopen = 1;
		} else {
			closeOverlay();
		}
		return false;
	});
	
	jQuery('#inline-ajax-search-form').keypress(function(e) { // IGNORE RETURN
		if (e.which == 13) {	return false;	}
	});

	
	// CONTENTS //
	
	var contentsopen = 0;
	jQuery('.contents_but, .contentsback').live('click', function(event) {
		if(contentsopen == 0) {
			clicky.log(this.href, 'Open Contents'); // CLICKY
		
			closeOverlay();
			if(jQuery('.contentsscreen .foathrobber').length == 1) {	
				getContents(cur_issue);
			}
			jQuery('html, body').animate({scrollTop: "0px" }, 0);
			jQuery(".contentsscreen").css({ height: jQuery(document).height()+"px", opacity: 1 });
			jQuery(".contentsscreen").show();
			setTimeout(function(){ jQuery(".contentsscreen").addClass('tdbackflip'); }, 50);
			contentsopen = 1;
		} else {
			closeOverlay();
		}
		return false;
	});
	
	
	// CLOSE OVERLAYS //
	
	function closeOverlay(){
		if(contentsopen == 1) {
			jQuery(".contentsscreen").removeClass('tdbackflip');
			jQuery(".contentsscreen").animate({ opacity: 0 }, 700, function() { jQuery(".contentsscreen").hide(); });
			contentsopen = 0;
		}
		if(searchopen == 1) {
			jQuery(".searchscreen").removeClass('tdbackflip');
			jQuery(".searchscreen").animate({ opacity: 0 }, 700, function() { jQuery(".searchscreen").hide(); });
			searchopen = 0;		
		}
	
	}
	
	
	// GET CONTENTS //
	
	function getContents(id){
		var updateCon = function(data) {
			jQuery(".contentsscreen .foathrobber").replaceWith(data.commands);
			var thwidth = jQuery(".dyncon").width();
			if(jQuery(".dyncon .dyninbox").width() <= thwidth) {
				jQuery("#nextcon").css({ opacity: 0 });
			}
			if(typeof(FOAcurpag) != 'undefined') {			
				if((FOAcurpag*244) >= thwidth) {
					var thwidthmove = (thwidth*-1) + 244;
					var movepages = Math.round(thwidth / (FOAcurpag*244));
					jQuery("#prevcon").animate({ opacity: 1 }, 350);
					jQuery(".dyncon .dyninbox").animate({ left: "+="+(movepages*thwidthmove)+"px" }, 350);
					
					if(((movepages+1)*thwidth*-1) <= (jQuery(".dyncon .dyninbox").width()*-1)) {
						jQuery("#nextcon").animate({ opacity: 0.25 }, 350);
					}
				}
			}
		}
		jQuery.ajax({
		  type: 'POST',
		  url: homedir+"as_getcon/"+id,
		  success: updateCon,
		  dataType: 'json'
		});
	}
});



// >>>> GLOBAL <<<< //


// UNMUTE (OLD FLASH?)

function unMute() {
	mainMute = 0;
}


// PLAY VIDEO SYSTEM + VARS //

var vidid = "";
var vidqual = "sd";
var curPlaying;
var mainMute = 0;
var adplay = 1;
var adtimeout;
var srvid = 0;
var nowplaying = '';
var promourl = '';
var promotitle = '';

// INITIAL PLAY TRIGGER //

function playVid(id, noad){
	jQuery('div').remove('.dynamicDiv');
	jQuery('div').remove('.foathrobberabs');
	if(jQuery('.playbar').length == 1)	{	closeVidBar();	}
	
	jQuery("#"+id).append("<div class=\"foathrobberabs foapa0\"></div>");
	
	setTimeout(function(){ jQuery('.foathrobberabs').animate({ opacity: 1 }, 800); }, 700);
	
	vidid = id;
	
	if(nowplaying == 'ad') {	nowplaying = ''; 	}
	
	if(noad == 1) { adplay = 0; }
	
	if (adplay == 1) {
		promourl = '';
		nowplaying = 'ad';
		jQuery.ajax({
		  type: 'POST',
		  url: homedir+"as_getad/",
		  success: goAd,
		  dataType: 'json'
		});
			var openTopBar = 1;
			if(jQuery("#"+vidid).parent().attr('class') == 'main_video') { // IF MAIN VID
				openTopBar = 0;	}
			if(jQuery('.fullscreenvidbox .invidbox').length == 1) { // IF FULL SCREEN VID
				openTopBar = 0; }
			
			if(openTopBar == 1) { // OPEN TOP BAR
			setTimeout(function(){
				openVidBar('Film On Air promo', 0, 0);
			}, 400);
		}
	}
	
	srvid = 0;
	jQuery.ajax({
	  type: 'POST',
	  url: homedir+"cfg_vidab.php?v="+id,
	  success: checkServ,
	  dataType: 'json'
	});
}


// PLAY AD //

var goAd = function(data) {	
	jQuery("#"+vidid+" .foathrobberabs").replaceWith("<div id=\"divflash"+vidid+"\" class=\"dynamicDiv\" style=\"width:"+jQuery("#"+vidid).width()+"px; height:"+Math.ceil((jQuery("#"+vidid).width()/854)*480)+"px;\"></div>");
	jQuery.ajax({ type: 'POST', url: homedir+"as_adcount/"+data.commands, dataType: 'json' });
	
	promourl = data.promo;
	promotitle = data.ptitle;
	doPromo();
	
	if(jQuery("#"+vidid).parent().attr('class') == 'main_video') { // IF MAIN VID
		jQuery("body").append("<a href=\"\" class=\"skipbut skipflash\">skip</a>");
		jQuery(".skipbut").css({ position: 'absolute', left: (jQuery('#'+vidid).offset().left+jQuery("#"+vidid).width()-50)+"px", top: (jQuery("#"+vidid).offset().top+jQuery('#'+vidid+' .blackbox').height()+4)+"px", zIndex: 99999 });	
	}
	
	if(jQuery.flash.available) {		
		jQuery(".dynamicDiv").flash({
			swf: homedir+'sites/all/themes/foa/foa18.swf', height: '100%', width: '100%', hasVersion: 9, scale: 'showall', allowFullScreen: true, allowscriptaccess: 'always', wmode: 'opaque',
			flashvars: {	vi: data.commands, noaut: 0, qa: "sd", srv: 1, isad: 1, nosnd: mainMute		}
		});	
	} else {
		var toPlay = gs1+"ads/"+data.commands+"_sd.mp4";
		var vidstring = "<video poster=\""+homedir+"/img/video/"+vidid+"_sml.jpg\" src=\""+toPlay+"\" controls=\"controls\" width=\""+jQuery("#"+vidid).width()+"\" height=\""+Math.ceil((jQuery("#"+vidid).width()/854)*480)+"\" autoplay=\"autoplay\" id=\"foavid\">Your browser doesn\'t support Flash or the HTML5 video format.</video>";
		jQuery(".dynamicDiv").html(vidstring);
		var foaVideo = document.getElementsByTagName('video')[0];
		foaVideo.addEventListener('ended',doneVid,false);
	}
	
	adplay = 0;
	adtimeout = setTimeout(function(){ adplay = 1; }, 45000);	
}

jQuery('.skipbut, .skipit').live('click', function(event) {
	clicky.log(this.href, 'Skip Ad'); // CLICKY

	doneVid();
	return false;
});

var checkServ = function(data) {
	if(data == 1){
		srvid = 1;
	} else if(data == 2){
		srvid = 2;
	} else { // FILE NOT FOUND
		var errormes = "Looks like you found our fail whale.. The video you're looking for couldn't be located. The video server guys probably screwed up though, not us. ^.^ <br /><br />You could give it a couple of minutes and try again..";
		jQuery("body").append("<div id=\"top_message\"><a href=\"javascript:toggleLayer('top_message');\" class=\"close_1\"></a>"+errormes+"</div>");
	}
	if(nowplaying != 'ad') {
		goVid();
	}
}

function doneVid() {
	closeVidBar();
	if(nowplaying == 'ad') { // check if donevid called from ad
		nowplaying = '';
		if(srvid != 0){
			goVid();
		}
	} else {
		setTimeout(function(){ jQuery('div').remove('.dynamicDiv'); }, 50); // TIMEOUT FOR IE7-8 FIX
	}
}

// PLAY VIDEO TRIGGER //

function goVid() {
	jQuery('a').remove('.skipbut');
	if(srvid == 1) { var selgs = gs1; } else { var selgs = gs2; }
	var toPlay = selgs+"awesome/"+vidqual+"/"+vidid+".mp4";
	
	jQuery.ajax({ type: 'POST', url: homedir+"as_videocount/"+vidid, dataType: 'json' });
	
	if (jQuery('#vid_body .promoblk .plnk').length == 1) { // if promo text vid page DIM
		jQuery('#vid_body .promoblk .plnk').animate({ opacity: 0.2 }, 1000);
	}
	
	var openTopBar = 1;
	if(jQuery("#"+vidid).parent().attr('class') == 'main_video') { // IF MAIN VID
		openTopBar = 0;	}
	if(jQuery('.fullscreenvidbox .invidbox').length == 1) { // IF FULL SCREEN VID
		openTopBar = 0; }
	
	if(openTopBar == 1) { // OPEN TOP BAR
		setTimeout(function(){
			var morelnk = "<a href=\""+jQuery("#"+vidid+" .rellink").attr('href')+"\" class=\"morevid\">"+jQuery("#"+vidid+" .rellink").text()+"</a>";
			openVidBar(jQuery("#"+vidid+" .link").text(), jQuery("#"+vidid+" .link").attr('href'), morelnk);
		}, 400);
	}

	if (jQuery("#"+vidid+" .foathrobberabs").length == 1) { // if no ad played
		jQuery("#"+vidid+" .foathrobberabs").replaceWith("<div id=\"divflash"+vidid+"\" class=\"dynamicDiv\" style=\"width:"+jQuery("#"+vidid).width()+"px; height:"+Math.ceil((jQuery("#"+vidid).width()/854)*480)+"px;\"></div>");
		if(jQuery.flash.available == false){
			var vidstring = "<video poster=\""+homedir+"/img/video/"+vidid+"_sml.jpg\" src=\""+toPlay+"\" controls=\"controls\" width=\""+jQuery("#"+vidid).width()+"\" height=\""+Math.ceil((jQuery("#"+vidid).width()/854)*480)+"\" autoplay=\"autoplay\" id=\"foavid\">Your browser doesn\'t support Flash or the HTML5 video format.</video>";
			jQuery(".dynamicDiv").html(vidstring);
		}
	}

	if(jQuery.flash.available) {
		setTimeout(function(){ 
			jQuery(".dynamicDiv").flash({
				swf: homedir+'sites/all/themes/foa/foa18.swf', height: '100%', width: '100%', hasVersion: 9, scale: 'showall', allowFullScreen: true, allowscriptaccess: 'always', wmode: 'opaque',
				flashvars: {	vi: vidid, noaut: 0, qa: vidqual, srv: srvid, isad: 0, nosnd: mainMute		}
			});
		}, 50); // TIMEOUT FOR IE7-8 FIX
	} else {	
		var foaVideo = document.getElementsByTagName('video')[0];
		foaVideo.src=toPlay;
		foaVideo.load();
		foaVideo.play();
		
		foaVideo.addEventListener('ended',doneVid,false);
	}
	curPlaying = vidid;
}


// VID PLAY BAR //

function openVidBar(title, turl, more) {
	var socbuts = ''; var morelink = '';

	if (turl != 0) {			socbuts = genSocial(turl, title);		}
	if(nowplaying == 'ad') {	title = title+" <a href=\"\" class=\"skipit but\">skip</a>";
	} else { 						
		if(jQuery('#movie_body').length != 1)	{ // IF NO MOVIE VIDS ON PAGE
			morelink = more;
		}
		var hdq = ''; var sdq = '';
		if (vidqual == 'hd') { hdq = ' select'; } else { sdq = ' select'; }
		title = title+" <div class=\"qual\"><a href=\"\" class=\"but"+sdq+"\">SD</a> <a href=\"\" class=\"but"+hdq+"\">HD</a></div>";
	}
	
	jQuery("body").append("<div class=\"playbar atopbox foasha\"><div class=\"now\">now playing:</div><div class=\"vidtit\">"+title+"</div>"+morelink+"<a href=\"\" class=\"close_1 closeplaybar\" title=\"Close video\"></a><div class=\"promoblk\"></div></div>");
	jQuery('.playbar').append(socbuts);
	jQuery('.playbar').css({ position: "fixed", marginLeft: 0, marginTop: 0, top: "9px", left: "0px", zIndex: "99999" });
	jQuery('.playbar').animate({ marginTop: "25px", opacity: "toggle" }, 400);
	
	doPromo();	
};

jQuery('.qual a').live('click', function(event) {
	var curvidqual = vidqual;
	jQuery('.qual a').removeClass('select');
	jQuery(this).addClass('select');
	vidqual = jQuery(this).text().toLowerCase();
	clicky.log(this.href, 'Change Video Quality '+vidqual); // CLICKY
	
	if((curvidqual != vidqual) && (nowplaying != 'ad')) {
		playVid(jQuery('.dynamicDiv').parent().attr("id"));
	}
	return false;
});

function closeVidBar() {
	jQuery('.playbar').animate({ marginTop: "0px", opacity: "toggle" }, 300, function() {	jQuery('div').remove('.playbar');	});
};

jQuery('.closeplaybar').live('click', function(event) {
	jQuery('div').remove('.dynamicDiv');
	closeVidBar();
	return false;
});


// IF PROMO //

function doPromo() {
	if(promourl != '') { // PROMO URL
		jQuery('.promoblk').html('<a href="'+promourl+'" class="plnk">'+promotitle+' &rarr;</a>');
	}
}


// SOCIAL BOX //

function genSocial (thurl, thtext) {
	return "<div class=\"soclbox\"><div class=\"pgbrk_share1\"><a href=\"\" rel=\"nofollow\">Like</a><div class=\"pgbrk_share5 foapa0\"><iframe src=\"http://www.facebook.com/plugins/like.php?href="+escape(thurl)+"&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21\" scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:450px; height:21px;\" allowTransparency=\"true\"></iframe></div></div><div class=\"pgbrk_share2\"><a href=\"\" rel=\"nofollow\">Tweet</a><div class=\"pgbrk_share4 foapa0\"><a href=\"http://twitter.com/share\" class=\"twitter-share-button\" data-url=\""+thurl+"\" data-text=\""+thtext+"\" data-count=\"none\" data-via=\"filmonair\">Tweet</a><script type=\"text/javascript\" src=\"http://platform.twitter.com/widgets.js\"></script></div></div><div class=\"pgbrk_share3\"><a href=\"\" rel=\"nofollow\">+1</a><div class=\"pgbrk_share6 foapa0\"><g:plusone size=\"medium\" count=\"false\" href=\""+thurl+"\"></g:plusone><script type=\"text/javascript\" src=\"http://apis.google.com/js/plusone.js\"></script></div></div></div>";
};


// SIMPLE TOGGLE DIV //

function toggleLayer(whichLayer) {
	jQuery("#"+whichLayer).slideToggle(300);
};
var FOAcurpag;

jQuery(document).ready(function () {

	// ART COUNTER //

	if(cur_node) {
		jQuery.ajax({ type: 'POST', url: homedir+"aj_artcount/"+cur_node, dataType: 'json' });
	}
	
	
	// LOGO FADE-IN
	
	if(jQuery('#coverlogo').length) {
		jQuery('#coverlogo').animate({ opacity: 1 }, 400);
	}
	
		
	// PAGEBREAK //
	
	if(jQuery("#pagebreak_titles li h3").length == 1) {
		FOAcurpag = (jQuery("#pagebreak_titles li h3").position().top+20)/26;
		
		var pagebreak = 0;
		var pagetitpos = jQuery("#pagebreak_titles li h3").position().top-16;
		jQuery("#pagebreak_titles").animate({ marginTop: "-"+(pagetitpos)+"px" }, 500);
		jQuery("#pagebreak_blok .unselect").css({ opacity: 0 });

		jQuery(".pagebreak_up, .pagebreak_upwh").click(function() {
			clicky.log(this.href, 'Magazine Pagebreak'); // CLICKY
			if(pagebreak == 0){
				jQuery(".pagebreak_up, .pagebreak_upwh").css({ "background-position" : "-40px 0px" });
				jQuery("#pagebreak_blok").animate({ marginTop: "-"+(jQuery("#pagebreak_titles").height()+10)+"px", height: (jQuery("#pagebreak_titles").height()+50)+"px" }, 500);
				jQuery("#pagebreak_titles").animate({ marginTop: "26px" }, 500);
				jQuery("#pagebreak_blok .unselect").animate({ opacity: 0.6 }, 500);
				jQuery("#pagebreak_blok .whline").animate({ opacity: 0.8 }, 500);
				jQuery("#pagebreak_blok .soclbox").animate({ opacity: 0 }, 500);
				jQuery("#pagebreak_titles h3").animate({ width: "600px" }, 500);
				pagebreak = 1;
			} else { 
				jQuery(".pagebreak_up, .pagebreak_upwh").css({ "background-position" : "0px 0px" });
				jQuery("#pagebreak_blok").animate({ marginTop: "0px", height: "40px" }, 500);
				jQuery("#pagebreak_titles").animate({ marginTop: "-"+(pagetitpos)+"px" }, 500);
				jQuery("#pagebreak_blok .unselect").animate({ opacity: 0 }, 500);
				jQuery("#pagebreak_blok .soclbox").animate({ opacity: 1 }, 500);
				jQuery("#pagebreak_blok .whline").animate({ opacity: 0 }, 500);
				jQuery("#pagebreak_titles h3").animate({ width: "244px" }, 500);
				pagebreak = 0;
			}
			return false;
		});
	}
	
	
	// PLAY FULLSCREEN CLICK
	
	jQuery('.playfullscreen').live('click', function(event) {
		clicky.log(this.href, 'Play Video Magazine Full Screen'); // CLICKY
	
		var id = jQuery(this).attr("id");
		
		var prepareFullscreen = function(data) {
			jQuery(".fullscreenvidbox").html(data.fullscreenvid);
			jQuery(".fullscreenvidbox .invidbox").animate({ opacity: 1 }, 600);
			goResMag();
			
			var hdq = ''; var sdq = ''; var qualbuts;
			if (vidqual == 'hd') { hdq = ' select'; } else { sdq = ' select'; }
			qualbuts = " <div class=\"qual\"><a href=\"\" class=\"but"+sdq+"\">SD</a> <a href=\"\" class=\"but"+hdq+"\">HD</a></div>";
			
			jQuery("<div class=\"infobox foapa85\"></div><a href=\"\" class=\"closebut foabut\">Close</a>"+qualbuts).appendTo('.fullscreenvidbox');

			var social = genSocial(jQuery(".fullscreenvidbox .invidbox .link").attr('href'), jQuery(".fullscreenvidbox .invidbox .link").text());
			jQuery(social).appendTo('.fullscreenvidbox');
			
			jQuery('html, body').animate({ scrollTop: 0 }, 0);
			
			setTimeout(function(){ autoPlayVid("fullscreenvidbox .invidbox"); }, 1050);
		}		
		
		jQuery("body").append("<div class=\"fullscreenvidbox tdflip foapa70\"><div class=\"vidthrob\"></div></div>");
		jQuery(".fullscreenvidbox").animate({ opacity: 1 }, 300);
		setTimeout(function(){ jQuery(".fullscreenvidbox").addClass('tdbackflip'); }, 50);		
		
		jQuery.ajax({
		  type: 'POST',
		  url: homedir+"as_fullscreenvid/"+id,
		  success: prepareFullscreen,
		  dataType: 'json'
		});
		return false;
	});
	
	jQuery('.fullscreenvidbox .closebut').live('click', function(event) {
		jQuery(".fullscreenvidbox").removeClass('tdbackflip');
		jQuery(".fullscreenvidbox").animate({ opacity: 0 }, 700);
		setTimeout(function(){ jQuery('div').remove('.fullscreenvidbox'); }, 1100);
		return false;
	});
	
	
	// WINDOW CHANGE MAG (FULL SCREEN VID)
	
	jQuery(window).bind('resize', function() { goResMag() });
	var changeVidLater;
	
	function goResMag () {
		if(jQuery('.fullscreenvidbox .invidbox').length == 1) {	
			if((jQuery(window).width()/(jQuery(window).height()-72)) > 1.77) { // IS TOO WIDE
				var targetvidwi = Math.ceil(((jQuery(window).height()-72)/720)*1280);
				var targetvidle = Math.ceil((jQuery(window).width()-targetvidwi)/2);
				jQuery(".fullscreenvidbox .invidbox").css({ height: (jQuery(window).height()-72)+"px", width: targetvidwi+"px", left: targetvidle+"px", top: "40px" });
				jQuery(".dynamicDiv").css({ height: (jQuery(window).height()-72)+"px", width: targetvidwi+"px" });
				
			} else {
				var targetvidhe = Math.ceil((jQuery(window).width()/1280)*720);
				var targetvidto = Math.ceil((jQuery(window).height()-targetvidhe)/2);
				jQuery(".fullscreenvidbox .invidbox").css({ height: targetvidhe+"px", width: jQuery(window).width()+"px", left: "0px", top: targetvidto+"px" });
				jQuery(".dynamicDiv").css({ height: targetvidhe+"px", width: jQuery(window).width()+"px" });
			}
			if(iOS == 1) {
				//
			};
		}
	};
	
	
	// POLL <<< OLD
	
	jQuery(".form-item").mouseenter(function() { 
		jQuery(this).children('.form-bol').fadeTo("fast", 1);
	}).mouseleave(function() {
		jQuery(this).children('.form-bol').fadeTo("fast", 0);
	});

	jQuery(".voterform .form-item").click(function() { 
		jQuery(this).find("input").attr("checked", "checked");
		jQuery("#poll-view-voting").submit();
	});

	
});


// IN MAG PAGE SCROLL

function scrollInPage(theclass){
	if(iOS == 1) {
		jQuery(theclass).css({"overflow-y" : "scroll", "-webkit-overflow-scrolling" : "touch"});
	} else {
		jQuery(theclass).niceScroll({cursorcolor:"#0096ce",  cursorwidth:"2px", cursorborder: "0px solid #FFF", background:"#a0ffa0"});		
	}
}

// STOP ALL VIDS //

function stopAllVids(){ 
	jQuery('div').remove('.dynamicDiv');
	closeVidBar();
}


// AUTOPLAY VIDEO autoPlayVid(parent class)

function autoPlayVid(theclass, noad){ 
	var id = jQuery("."+theclass+" .mag_mov li").attr("id");
	playVid(id, noad);
}


// PLAY MAG VID <<< REWRITE

function playMagVid(id, vidid, noautr, repeatr){ 

	var divFla = document.createElement("div");
	divFla.id = "divflash"+id;
	divFla.className ="dynamicDiv";
	divFla.style.position = "absolute";
	divFla.style.zIndex = 9999;
	divFla.style.top = jQuery("#"+id).offset().top+"px";
	divFla.style.left = jQuery("#"+id).offset().left+"px";
	divFla.style.width = jQuery("#"+id).width()+"px";
	divFla.style.height = jQuery("#"+id).height()+"px";

	curPlaying = id;
	
	jQuery(divFla).flash({
	swf: homedir+'sites/all/themes/foa/magvid.swf',
	height: '100%',
	width: '100%',
	hasVersion: 9,
	scale: 'exactfit',
	allowFullScreen: false,
	allowscriptaccess: 'always',
	wmode: 'transparent',
	flashvars: {
		thevid: vidid,
		noaut: noautr,
		rpt: repeatr
		}
	});
				
	jQuery(divFla).appendTo("body");
	
};
jQuery(function() {

o1=new Object();
var foaTimer=new Array();
	
foaMain = function() {	

	o1.DangTel = 1;

	o1.DangmTxt = function (){
		if(o1.DangTel < 8) {
			jQuery("#adangmcover .dangbl"+o1.DangTel).animate({ opacity: 1 }, 1000);
			o1.DangTel++;
			foaTimer[0] = setTimeout(function(){ o1.DangmTxt(); }, 500);
		} else {
			o1.DangEnd();
		}
		
	}
	o1.DangmTxt();
	
	o1.DangEnd = function (){
		foaTimer[1] = setTimeout(function(){ jQuery("#dangmetfoalogo").animate({ opacity: .85 }, 400); }, 1600);
		setTimeout(function(){ goCovers(); }, 2200);
	}
	
}
	
foaMain();
	
});;

