jQuery(window).ready(function(){
	if (typeof(Custom)=="object") {
		Custom.init();
	}
});

function toggleLayer( whichLayer )
{
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

 function bookmark(url, title) {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title);
	} 
 }
 
 function writeBookmarkLink(url, title, innerHTML) {
	if (typeof(url)=='undefined') {
		url = location.href;		
	}
	if (typeof(title)=='undefined') {
		title = document.title;
	}
	if (typeof(innerHTML)=='undefined') {
		innerHTML = 'Bookmark this page';
	}
 
	if (window.sidebar || window.external) {
		document.write('<a href="javascript:bookmark(\''+url+'\',\''+title+'\')">'+innerHTML+'</a>');
	} else if (window.opera && window.print) {
		document.write('<a href="'+url+'" rel="sidebar">'+innerHTML+'</a>');
	}
 }
 
 function prepareEditors() {
	editor1.prepareSubmit();
	editor2.prepareSubmit();
 }
 
 function validateMsgForm() {
	var success = document.forms.message.recid.value!=-1;
	if (success==false) {
		alert("Please choose a recipient.");	
	}
	return success;
 }
 
function validateContactForm() {
	if (document.forms.contactus.cfEmail.value.indexOf("@")==-1 || document.forms.contactus.cfEmail.value.indexOf(".")==-1) {
		alert("Please enter valid e-mail address.");
		return false;
	} else if (document.forms.contactus.cfMessage.value.length<1) {
		alert("Please enter a message.");
		return false;
	}
	return true;
 }
 
 function confirmProceeding(url,question) {
	if (typeof(url)=='undefined') {
		question="Are you sure?";		
	}
	if (confirm(question)) {
		window.location=url;
	}
 }
 
 function goWhenConfirmed(targetLocation,message) {	
	if (window.confirm(message)) {
		document.location=targetLocation;
	}
}

function saveAndGoTo(url) {
	$('maction').value='goTo';
	$('mid').value=url;
	document.forms.mForm.submit();
}

function saveAndGoWhenConfirmed(url,message) {
	if (window.confirm(message)) {
		$('maction').value='goTo';
		$('mid').value=url;
		document.forms.mForm.submit();
	}
}

function StartDropping(node)
{ 
node.onmouseover=function() { this.id+="-on"; }
node.onmouseout=function() { this.id=this.id.replace("-on", ""); }
}

var tTabs=null;

initJs = function() {
	if (document.all&&document.getElementById) { 
		StartDropping(document.getElementById("tabmybulletfilm")); 
		StartDropping(document.getElementById("tabpremium")); 
		StartDropping(document.getElementById("tabfilms"));
		StartDropping(document.getElementById("tabevents"));
		StartDropping(document.getElementById("tabcommunity"));
		StartDropping(document.getElementById("tabfilmmaking"));
		StartDropping(document.getElementById("tabhelp"));
	}
	
	if (typeof(staticLeftCol)!='undefined' && !staticLeftCol) {
		tTabs=setTimeout("changeTab(2);",12000);
	}
	if (undefined!=document.getElementById("mainwindow2")) {
		tWindows=setTimeout("changeMainWindow(2);",5000);
	}
	if (undefined!=document.getElementById("embed_string")) {
		setPasteCode("");
	}
}
window.onload=initJs;

var activeTab=1;

function changeTab(newTab) {
	document.getElementById("tab"+activeTab+"a").style.display="none";
	document.getElementById("tab"+activeTab+"ia").style.display="block";
	document.getElementById("tab"+newTab+"a").style.display="block";
	document.getElementById("tab"+newTab+"ia").style.display="none";
	activeTab=newTab;
	
	newTab++;
	if (newTab>6) {
		newTab=1;
	}
	clearTimeout(tTabs);
	tTabs=setTimeout("changeTab("+newTab+");",12000);
}

var tWindows=null;
var activeWindow=1;
var windowPhase='still';

function changeMainWindow(newWindow) {
	if (windowPhase=="still") {
		opacity("mainwindow"+activeWindow,100,0,300);
		windowPhase='fade out';
		clearTimeout(tWindows);
		tWindows=setTimeout("changeMainWindow("+newWindow+");",300);
		return;
	}
	if (windowPhase=="fade out") {
		document.getElementById("mainwindow"+activeWindow).style.display="none";
		changeOpac(0,"mainwindow"+newWindow);
		document.getElementById("mainwindow"+newWindow).style.display="block";
		opacity("mainwindow"+newWindow,0,100,300);
		windowPhase='still';		
		activeWindow=newWindow;
		
		newWindow++;
		if (newWindow>windowCount) {
			newWindow=1;
		}
		
		clearTimeout(tWindows);
		tWindows=setTimeout("changeMainWindow("+newWindow+");",windowDurations[activeWindow]!=undefined?windowDurations[activeWindow]:4000);
		return;
	}
}

function nextMainWindow() {
	var newWindow=activeWindow+1;
	if (newWindow>windowCount) {
		newWindow=1;
	}
	changeMainWindow(newWindow);
}

function prevMainWindow() {
	var newWindow=activeWindow-1;
	if (newWindow<1) {
		newWindow=windowCount;
	}
	changeMainWindow(newWindow);
}

function opacity(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++)
			{
			setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function shiftOpacity(id, millisec) {
	//if an element is invisible, make it visible, else make it ivisible
	if(document.getElementById(id).style.opacity == 0) {
		opacity(id, 0, 100, millisec);
	} else {
		opacity(id, 100, 0, millisec);
	}
}

function blendimage(divid, imageid, imagefile, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//set the current image as background
	document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";
	
	//make image transparent
	changeOpac(0, imageid);
	
	//make new image
	document.getElementById(imageid).src = imagefile;

	//fade in image
	for(i = 0; i <= 100; i++) {
		setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
		timer++;
	}
}

function getOpacity(id) {
	//standard opacity is 100
	var currentOpac = 100;
	
	//if the element has an opacity set, get it
	if(document.getElementById(id).style.opacity < 100) {
		currentOpac = document.getElementById(id).style.opacity * 100;
	}
	
	return currentOpac;
}

function currentOpac(id, opacEnd, millisec) {
	var currentOpac = getOpacity(id);

	//call for the function that changes the opacity
	opacity(id, currentOpac, opacEnd, millisec)
}

function showBenefits() {
	jQuery.ajax({
	  url: "/register/benefits?plain=1",
	  success: function(html){
			//add modal background
			jQuery('<div />').addClass('lightbox_bg').appendTo('body').show();
			//add modal window
			jQuery('<div />').html("<div onclick='hideBenefits();'><p style='float:right;'><a href='javascript:hideBenefits();' style='text-decoration:none; border:1px solid #838057; padding:0 3px;' title='close window'>X</a></p><h2 class='sifr'>Benefits of registering with Bulletfilm</h2>"+html+"<p><a href='javascript:hideBenefits();'>Close</a></p></div>").addClass("modal").addClass('contents').appendTo('body');
	  }
	});	
}

function hideBenefits() {
	jQuery('.lightbox_bg').hide();
	jQuery('.modal').hide();
}

function sendNewPassword() {
	jQuery('#submitting').show();
	jQuery("#result").hide();
		
	var username=jQuery('#fp_username input').val();
	var email=jQuery("#fp_email input").val();
	
	jQuery.post('/set/sendNewPassword', jQuery("#forgotpass form").serialize(), 
		function (data, textStatus) { 
			if (data!="OK") {
				jQuery("#result").html(data);
				jQuery("#result").show();
				//setTimeout('jQuery("#result").hide("slow");',4000);
				jQuery("#submitting").hide();
			} else {
				jQuery("#forgotpass form").hide();
				jQuery("#result").html("Password has been sent.");
				jQuery("#result").show();
			}
		}
	);
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function getMeta() {
	var uri=jQuery("#uri_address input").attr("value");
	uri=uri.replace(/(http:\/\/((www\.)?bulletfilm\.com)?)?/i,"").replace(/^(.+)\/\s*$/,"$1");
	jQuery("#uri_address input").attr("value",uri);
	jQuery("#visituri").html("<a href='"+escape(uri)+"' target='_blank'>Visit this address</a>");
	jQuery.ajax({
	  url: "/get/metatags?uri="+URLEncode(uri),
	  success: function(html){
			var meta=html.split('##');
			jQuery("#defaulttitle").html("<span class='annotation'>Current title:</span> "+meta[0]);
			jQuery("#defaultdesc").html("<span class='annotation'>Current description:</span> "+meta[1]);
			jQuery("#defaultkw").html("<span class='annotation'>Current keywords:</span> "+meta[2]);
	  }
	});	
}

function loadCalPage() {
	jQuery.ajax({
	  url: "/cache.php?name=festCalPage"+calPage,
	  success: function(html){
			jQuery("#calPage").replaceWith(html);
	  }
	});	
}
function calPrevMonth() {
	if (calPage>1) {
		calPage--;
		loadCalPage();
	}
}

function calNextMonth() {
	if (calPage<calPageCount) {
		calPage++;
		loadCalPage();
	}
}

function popup(url, width, height, scrollbars)
{ 
	if (scrollbars==undefined) { 
		scrollbars="yes"; 
	} 
	window.open(url,"_blank","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars="+scrollbars+", resizable=yes, width="+width+", height="+height);
}

var liveTimer=null;
var liveTopicTimer=null;

function setUpLiveUpdate() {
	liveTimer=setTimeout("updateLiveMessages();",5000);
	
	if (!liveTopicTimer) {
		liveTopicTimer=setTimeout("updateLiveTopic();",60000);
	}
}

function updateLiveMessages() {
	jQuery.ajax({
	  url: "/get/livemessages/"+jQuery("#lastlvmid").val(),
	  success: function(data){
			var items=data.split('##');
			if (items[0].length>0) {
				jQuery("#newmessages").replaceWith(items[0]);
			}
			setUpLiveUpdate();
			if (items[1]) {
				jQuery("#lastlvmid").val(items[1]);
			}
	  }
	});	
}

function updateLiveTopic() {
	jQuery.ajax({
	  url: "/get/liveheader",
	  success: function(html){
			jQuery("#live-header").html(html);
			liveTopicTimer=setTimeout("updateLiveTopic();",60000);
	  }
	});	
}

function showFilmTab(tabName) {
	jQuery(".film-tab").hide();
	jQuery("#film-tab-"+tabName).fadeIn();
	jQuery(".fw-tab").removeClass("fw-tab-active");
	jQuery("#fw-tab-"+tabName).addClass("fw-tab-active");
}

function thumb(direction,objectId) {
	jQuery.ajax({
		url: "/set/thumb/"+direction+"/"+objectId,
		success: function(html){
			jQuery("#thumbs").html(html);
		}
	});	
}

function sendNewComment() {
	var comment=jQuery("#yourcomment").val();
	if (comment.length>=3) {
		jQuery("#rf-send-button").hide();
		jQuery("#rf-sending-button").show();
		setTimeout('jQuery("#rf-sending-button").fadeOut();',3000);
		jQuery.ajax({
			type: 'POST',
			url: "/set/comment", 
			data: jQuery("#new-comment-form").serialize(), 
			success: function (data) { 
				var elements=data.split("##");
				jQuery("#rf-sending-button").fadeOut();
				jQuery("#added-comment").replaceWith(elements[1]);
				jQuery("#yourcomment").val("");
				var commentCount=jQuery('#comment-count').text();
				if (commentCount=="NO") {
					commentCount="0";
					jQuery('#comments-word').text(" COMMENT");
				}
				if (commentCount==1) {
					jQuery('#comments-word').text(" COMMENTS");
				}
				jQuery('#comment-count').text(parseInt(commentCount)+1);
				var currentHref = window.location.href;
				window.location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#comment"+elements[0];
			}
		});
	}
}

function commentPleaseLogIn(encodedUri) {
	jQuery("#yourcomment").addClass("new-comment-log-in"); 
	jQuery("#yourcomment").attr("disabled","disabled"); 
	jQuery("#yourcomment").text("You need to be logged in"); 
	setTimeout('window.location="/register/signin?from='+encodedUri+'";',2000)
}

function showVideoEmbedCode() {
	jQuery("#embed").toggle("slow");
}