Event.observe(window, 'load', init, false);
var imgratio ;
var browserratio ;
var ajaxurl = '/ajax/';	// Where to post any AJAXy stuff
var checked = false;
var selected ;  	// Contains any selected checkboxes

var $jq = jQuery.noConflict();	// We need Prototype not to break

$jq(document).ready(function($) {
	$jq('a[rel*=facebox]').facebox()
	// Set up drop down menus
	$jq("#menu li").hover(
		function(){ $jq("ul", this).fadeIn("fast"); }, 
		function() { } 
	);
	if (document.all) {
		$jq("#menu li").hoverClass ("sfHover");
	}
});

$jq.fn.hoverClass = function(c) {
	return this.each(function(){
		$jq(this).hover( 
			function() { $jq(this).addClass(c);  },
			function() { $jq(this).removeClass(c); }
		);
	});
};	

function init(){
}

function doCheck(strForm){
	// Check / uncheck all the checkboxes in form ID strForm
    if(strForm){
        objForm = document.getElementById(strForm);
        for(i=0; i < objForm.elements.length; i++)
            if(objForm.elements[i].type == "checkbox")
                if(checked == false)
                    objForm.elements[i].checked = true;
                else
                    objForm.elements[i].checked = false;
        if(checked == false)
            checked = true;
        else
            checked = false;
    }
}


function makeEditable(id,param,lines,width){
	Event.observe(id, 'click', function(){edit($(id),param,lines,width)}, false);
	Event.observe(id, 'mouseover', function(){showAsEditable($(id))}, false);
	Event.observe(id, 'mouseout',  function(){showAsEditable($(id), true)}, false);
}

function edit(obj,param,lines,width){
	Element.hide(obj);
	var content = obj.innerHTML.replace(/\<br\>/gi, "\n");
	content = content.replace(/(<([^>]+)>)/g, "");
	content = content.replace(/.$/g,"");
	content = content.replace(/\"/g,"&quot;");
	content = content.replace(/Click\ to\ add\ a\ description/g,"");
	content = content.replace(/Click\ to\ add\ a\ caption/g,"");

	//var content = content.replace(/\n\n/gi, "\n");
	if (lines=='multi') {
		var textarea = '<div id="'+obj.id+'_editor"><textarea id="'+obj.id+'_edit" name="'+obj.id+'" rows="5" cols="65" style="width:'+width+'px">'+content+'</textarea><br />';
	} else {
		var textarea = '<div id="'+obj.id+'_editor" style="display:inline"><input type="text"  id="'+obj.id+'_edit" name="'+obj.id+'" rows="4" size="40" value="'+content+'" style="width:'+width+'px" />';
	}
	var button	 = '<div style="display:inline"><input id="'+obj.id+'_save" type="button" value="Save" />  <input id="'+obj.id+'_cancel" type="button" value="Cancel" /><br clear="left" /></div></div>';
	
	new Insertion.After(obj, textarea+button);	
		
	Event.observe(obj.id+'_save', 'click', function(){saveChanges(obj,param)}, false);
	Event.observe(obj.id+'_cancel', 'click', function(){cleanUp(obj)}, false);
	
}

function showAsEditable(obj, clear){
	if (!clear){
		Element.addClassName(obj, 'editable');
	}else{
		Element.removeClassName(obj, 'editable');
	}
}

function saveChanges(obj,param){
	var new_content	=  escape($F(obj.id+'_edit'));
	var new_content = new_content.replace(/\%A0/g,"");
	var new_content = new_content.replace(/\+/g,"%2B");
	obj.innerHTML	= "Saving...";
	cleanUp(obj, true);

	var success	= function(t){editComplete(t, obj);}
	var failure	= function(t){editFailed(t, obj);}

	var pars = 'ajax=edit&id='+obj.id+'&content='+new_content+'&param='+param;
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});

}

function cleanUp(obj, keepEditable){
	Element.remove(obj.id+'_editor');
	Element.show(obj);
	if (!keepEditable) showAsEditable(obj, true);
}

function editComplete(t, obj){
	obj.innerHTML	= t.responseText;
	showAsEditable(obj, true);
}

function replyComment(commentId,commentFrom) {
	document.getElementById('comment_info').innerHTML = '<div class="waitmsg"><span style="float:left">Replying to <a href="#comment' + commentId + '" onmouseover="highlightComment(' + commentId +')" onmouseout="unHighlightComment(' + commentId +')">comment ' + commentId + '</a> by ' + commentFrom + '</span> &nbsp; <span style="float:right"><a href="#comment_form" onClick="clearComment()" class="button">CANCEL</a></span></div>';
	document.getElementById('in_reply_to').value = commentId ;

}

function clearComment() {
	document.getElementById('comment_info').innerHTML = '';
	document.getElementById('in_reply_to').value = '';
}

function commentPosted(t,obj) {
	obj.innerHTML	+= t.responseText;
	document.getElementById('comment_info').innerHTML='';
	document.getElementById('comment_text').style.visibility='visible';
	document.getElementById('comment_submit').style.visibility='visible';
}

function editFailed(t, obj){
	obj.innerHTML	= 'Sorry, the update failed.';
	cleanUp(obj);
}


function submitComment() {
	var photo_id = document.getElementById('photo_id').value;
	var in_reply_to = document.getElementById('in_reply_to').value ;
	var comment_text = escape(document.getElementById('comment_text').value);
	var comment_text = comment_text.replace(/\+/g,"%2B");
	var pars = 'ajax=postcomment&photo_id='+photo_id+'&comment_text='+comment_text+'&in_reply_to='+in_reply_to;
	var obj = $('new_comments');

	if (comment_text=='') {
		document.getElementById('comment_info').innerHTML='<div class="waitmsg">You must type a comment!</div>' ;
	} else {
		document.getElementById('comment_info').innerHTML='<div class="waitmsg">Posting comment...</div>' ;
		document.getElementById('comment_text').value='';
		document.getElementById('comment_text').style.visibility='hidden';
		document.getElementById('comment_submit').style.visibility='hidden';

		var success	= function(t){commentPosted(t, obj);}
		var failure	= function(t){editFailed(t,'comment_form');}
		var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
	}
}

function updateOnline() {
	var pars = 'ajax=online';
	var obj = $('users_online');
	var response	= function(t){obj.innerHTML=t.responseText;}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
	setTimeout("updateOnline()",20000);
}

function delPhoto(photo_id) {
	var obj = document.getElementById('popupmsg');
	html = '<div class="boxheading">Delete Photo</div><div class="msg"><p>Are you sure you want to permanently delete this photo?</p><p>This cannot be undone.</p></div><div class="buttoncontainer"><a href="#popupmsg" rel="facebox" onclick="confirmDelPhoto(\'' + photo_id + '\')" class="button">DELETE</a> <a href="javascript:cancelPopup()" class="button">CANCEL</a></div>';
        obj.innerHTML = html ;
	jQuery.facebox(html);
}

function delPhotoFromAlbum(album_id,photo_id) {
	html = '<div class="boxheading">Remove Photo</div><div class="msg"><p>Are you sure you want to remove this photo from the album?</p><p>This will not physically delete the photo from your photoreel.</p></div><div class="buttoncontainer"><a href="?del=' + photo_id + '" class="button">REMOVE</a> <a href="javascript:cancelPopup()" class="button">CANCEL</a></div>';
	jQuery.facebox(html);
}

function delAlbum(album_name,album_id) {
	var obj = document.getElementById('popupmsg');
	var html = '<div class="boxheading">Delete Album</div><div align="center"><p>Are you sure you want to delete the album \'' + album_name + '\'?</p><p><a href="?del=' + album_id + '" class="button">DELETE</a> <a href="javascript:cancelPopup()" class="button">CANCEL</a></p></div>';
        obj.innerHTML = html ;
}

function addPhotoToAlbum(photo_id) {
	var pars = 'ajax=addtoalbum&photo_id='+photo_id;
	var response	= function(t){jQuery.facebox(t.responseText);}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
}

function confirmAddPhotoToAlbum(photo_id) {
	var albums = document.getElementById('album_id') ;
	var albumString = '&action=confirm&';
	for (var i = 0; i < albums.options.length; i++) {
		if (albums.options[i].selected) {
			albumString += 'albums[' + i +']=' + albums.options[i].value +'&';
		}
	}
	var pars = 'ajax=addtoalbum&photo_id='+photo_id + albumString ;
	var response	= function(t){jQuery.facebox(t.responseText);}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
}

function cancelPopup() {
	document.getElementById('popupmsg').innerHTML = '';
	jQuery(document).trigger('close.facebox')
}

function createAlbum() {
	var obj = document.getElementById('popupmsg');
	var html = '<div class="boxheading">Create Album</div><form action="./" id="create" name="create" style="margin:0px" method="POST"><div class="msg">Album Name: ';
	html += '<input type="text" name="album_name" size="32" maxlength="32" id="album_name" value="Untitled Album" onclick="this.value=\'\'" /> ';
	html += '</div><div class="buttoncontainer"><input type="hidden" name="action" value="create" />';
	html += '<input class="button" type="submit" value="CREATE"> <input type="hidden" name="action" value="create"> ';
        html += '<input type="button" class="button" value="CANCEL" onClick="cancelPopup()"> ';
	html += '</div></form>';
	jQuery.facebox(html);
	obj.innerHTML = html ;
}

function editTags(photo_id) {
	// Pop up text box for editing
	var pars = 'ajax=edittags&photo_id='+photo_id
	var response    = function(t){jQuery.facebox(t.responseText);}
        var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
}

function updateTags(photo_id) {
	var tags = escape(document.tagform.photo_tags.value);
	var pars = 'ajax=edittags&mode=update&photo_id='+photo_id+'&tags='+tags
	var response    = function(t){jQuery.facebox(t.responseText);}
        var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
}

function tagsearch() {
	var inputbox = document.getElementById("tag_search");
	var query = document.getElementById("tag_search").value.replace(/[^A-Za-z0-9]/g,"");
	if (query.length>0) {
		location.href='/browse/tags/' + query +'/';
	} else {
		inputbox.value ='';
	}
}

function confirmDelPhoto(photo_id) {
	var pars = 'ajax=delphoto&photo_id='+photo_id+'&action=confirm'
	var obj = $('popupmsg');
	var response	= function(t){obj.innerHTML=t.responseText;}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
	pathArray = window.location.pathname.split( '/' );
	newPath = '/' + pathArray[1] + '/'; 
	html = '<div class="boxheading">Photo Deleted</div><div class="msg">The photo has been deleted.</div><div class="buttoncontainer"><a href="' +newPath+'" class="button">OKAY</a></div>';
	jQuery.facebox(html);
}

function delComment(commentID) {
	var commenttext = document.getElementById('comment_text'+commentID).innerHTML;
	document.getElementById('popupmsg').innerHTML = '<div class="boxheading">Delete Comment</div><div class="msg">Are you sure you want to delete this comment?</div><div class="buttoncontainer"><a href="#'+commentID+'" onClick="confirmDelComment('+commentID+')" class="button">DELETE</a> <a href="#'+commentID+'" onClick="unDelComment('+commentID+',\''+escape(commenttext)+'\')" class="button">CANCEL</a></div>';

}

function unDelComment(commentID,commenttext) {
//	document.getElementById('comment_text'+commentID).innerHTML = unescape(commenttext) ;	
	document.getElementById('popupmsg').innerHTML ='';
	jQuery(document).trigger('close.facebox')
}

function confirmDelComment(commentID) {
	jQuery(document).trigger('close.facebox')
	var pars = 'ajax=delcomment&comment_id='+commentID
	var commentObj = 'comment'+commentID;
	var obj = $(commentObj);
	var response	= function(t){obj.innerHTML=t.responseText;}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
}

function photoDetails(photo_id,user_name) {
	// Show the details & social sharing links for a photo
	var pars = 'ajax=photodetails&id='+photo_id+'&user='+user_name;
	var obj = $('details_box');
	var success	= function(t){editComplete(t, obj);}
	var failure	= function(t){editFailed(t,'details_box');}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
}

function friendButton(user_name,action) {
	// Show the details & social sharing links for a photo
	var pars = 'ajax=friendbutton&user='+user_name+'&action='+action;
	var obj = $('friendbutton');
	var response    = function(t){obj.innerHTML=t.responseText;}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});

}

function highlightComment(commentID) {
	document.getElementById('comment'+commentID).className='highlightComment';
}

function unHighlightComment(commentID) {
	document.getElementById('comment'+commentID).className='comment';
}


function is_safari(){
        if(navigator.userAgent.indexOf("Safari")!=-1){
                return 1;
        }
        return 0;
}

function is_moz_one(){
        if(navigator.userAgent.indexOf("Mozilla/5.0")!=-1&&navigator.userAgent.indexOf("rv:1.0")!=-1){
                return 1;
        }
        return 0;
}

function upload_click_button(){
        if(is_safari()){
                upload_hide_form();
                document.getElementById("upload_form").submit();
        }
        return true;
}

function upload_submit_form(){
        if(! is_safari()&& ! is_moz_one()){
                upload_hide_form();
        }
        return true;
}

function upload_hide_form(){
        document.getElementById("upload_form_container").style.display="none";
        document.getElementById("upload_notes").style.display="none";
        document.getElementById("uploading_container").style.display="block";
}


function faves(username,photoid) {
	// Add or remove a Fave
        var pars = 'ajax=faves&photo_id='+photoid;;
        var response     = function(t){
		photoDetails(photoid,username);
	}
        var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
}

function showImg(img,w,h) {

	// Hack to cope with broken IE6
	temp=navigator.appVersion.split('MSIE');
	ieVer=parseInt(temp[1]);
	if (ieVer<7) {
		document.write('<html><body style="background:black;text-align:center"><a href="javascript:history.go(-1)"><img src="' + img + '" alt="" title="Click to Close" border="0"  /></a></body></html>');
	} else {
		var lowimg = img.replace('/l/','/m/');
		document.getElementById("fullscreen").style.display='block';
		if (! document.getElementById("fullscreenimg")) {
			document.getElementById("fullscreen").innerHTML = '<a href="javascript:hideImg()"><img src="' + img + '" alt="" title="Click to Close" border="0" id="fullscreenimg" /></a>';
		}
		document.getElementById("allcontent").style.display='none';
		imgratio = w/h;
		window.onresize=resizeImg;
		setTimeout('resizeImg()',200);
	}
}

function resizeImg() {
	var myImage = document.getElementById("fullscreenimg") ;
	// Get browser width and height
 	if (typeof window.innerWidth != 'undefined') {
		// standards compliant
     		width = window.innerWidth,
      		height = window.innerHeight
 	}  else if (document.documentElement && document.documentElement.clientWidth) {
		// IE 6
       		width = document.documentElement.clientWidth,
       		height = document.documentElement.clientHeight
 	}  else {
		// old browsers
      		width = document.getElementsByTagName('body')[0].clientWidth,
      		height = document.getElementsByTagName('body')[0].clientHeight
		}

	browserratio = width/height;
	if (imgratio>browserratio){
		var w2 = width ;
		var h2 = parseInt(w2/imgratio);
		myImage.style.width=w2 +'px';
		myImage.style.height=h2 +'px';
		// vertical centering if needed
		var top = parseInt((height-myImage.height)/2); 
		top = top +'px';
		myImage.style.marginTop = top;
	} else {
		var h2 = height ;
		var w2 = parseInt(h2 * imgratio) ;
		myImage.style.height=h2 +'px';
		myImage.style.width=w2 +'px';
		myImage.style.marginTop = '0px';
	}
	document.getElementById("fullscreen").style.backgroundImage='url(/template/images/spacer.gif)';
}


function hideImg() {
	window.onresize=null;
	document.getElementById("fullscreen").style.display='none';
	document.getElementById("allcontent").style.display='block';
}


function trim (str) {
        return str.replace(/^s+/,'');
}


function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}

function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function delMessage(message_id,refreshPage) {
	var html = '<div class="boxheading">Delete Message</div><div class="msg">Are you sure you want to delete this message?</div><div class="buttoncontainer"><a href="javascript:confirmDelMessage(' + message_id + ',' + refreshPage + ')" class="button">DELETE</a> <a href="javascript:cancelPopup()" class="button">CANCEL</a></div>';
	jQuery.facebox(html);
}

function multiMarkMessage(action) {
	var pars = '';

	// First check we have something to mark
	var numMessages = 0;
	selected = new Array();
	objForm = document.getElementById('mailform');
	for(i=0; i < objForm.elements.length; i++) {
        	if(objForm.elements[i].type == "checkbox") {
			if (objForm.elements[i].checked == true) {
				selected.push(objForm.elements[i].name);
				numMessages++ ;
			}
		}
	}
	if (numMessages>0) {
		if (action==0) {
	        	pars += 'action=unread&ajax=multimarkmessage&message_ids=' ;
		} else if (action==1) {
	        	pars += 'action=read&ajax=multimarkmessage&message_ids=' ;
		}
	
		if (pars !='') {
			for(i=0; i < selected.length; i++) {
				pars += selected[i]+ ',';
			}
			var response = function(t){
				if (t.responseText) {
					var html = '<div class="boxheading">Delete Messages</div><div class="msg">' + t.responseText + '</div><div class="buttoncontainer"><a href="/messages/" class="button">OK</a></div>';
					jQuery.facebox(html);
				}
				location.href='/messages/';

			}
			var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
		}
	}
}

function confirmMultiDelMessage() {
        var pars = 'ajax=multidelmessage&message_ids=' ;
	for(i=0; i < selected.length; i++) {
		pars += selected[i]+ ',';
	}
	var response = function(t){
		if (t.responseText) {
			var html = '<div class="boxheading">Delete Messages</div><div class="msg">' + t.responseText + '</div><div class="buttoncontainer"><a href="/messages/" class="button">OK</a></div>';
			jQuery.facebox(html);
		}
		location.href='/messages/';
	}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
}

function multiDelMessage() {
	// Delete / Mark multiple messages

	// First check we have something to delete
	var numMessages = 0;
	selected = new Array();
	objForm = document.getElementById('mailform');
	for(i=0; i < objForm.elements.length; i++) {
        	if(objForm.elements[i].type == "checkbox") {
			if (objForm.elements[i].checked == true) {
				selected.push(objForm.elements[i].name);
				numMessages++ ;
			}
		}
	}

	if (numMessages >0) {
		var html = '<div class="boxheading">Delete Messages</div><div class="msg">Are you sure you want to delete the selected messages?</div><div class="buttoncontainer"><a href="javascript:confirmMultiDelMessage()" class="button">DELETE</a> <a href="javascript:cancelPopup()" class="button">CANCEL</a></div>';
	} else {
		var html = '<div class="boxheading">Delete Messages</div><div class="msg">You must select some messages to delete.</div><div class="buttoncontainer"><a href="javascript:cancelPopup()" class="button">OK</a></div>';
	}
	jQuery.facebox(html);
}

function confirmDelMessage(message_id,refreshPage) {
        var pars = 'ajax=delmessage&message_id='+message_id ;
	var message_obj = 'msg_' + message_id ;
	var obj = $(message_obj);
	var response	= function(t){obj.innerHTML=t.responseText; }
	//var html = '<div class="boxheading">Delete Message</div><div class="msg">Message deleted.</div><div class="buttoncontainer"><a href="/messages/" class="button">OK</a></div>';
	//jQuery.facebox(html);
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
	location.href='/messages/';
}

function sendNewMessage() {
        var pars = 'ajax=getfriendsformsg' ;
	var response    = function(t){
		html = '<div class="boxheading">Send New Message</div>';
		html += '<div align="center">' +t.responseText+'</div>';
		jQuery.facebox(html);
	}
	var myAjax = new Ajax.Request(ajaxurl, {method:'post', postBody:pars, onSuccess:response, onFailure:response});
}	

