// rating
function submit_rating(type, member_id, content_id, score, url)
{
	$('#rating_'+type+'_progress'+content_id).show();

	$.post(virpath+'index.php?hp=1&m=rate', {'type':type,'score':score,'member_id':member_id,'content_id':content_id},
		function(response) {
			var response = response.split("\n");
			if ( response.length == 2 )
			{
				if ( response[0] == 'ok' && response[1] )
				{
					if ( typeof(url) != 'undefined' ) {
						window.location = url;
					}
					else {
						var curr_score = parseFloat($('#rating_'+type+'_score'+content_id).html());
						var curr_votes = parseInt($('#rating_'+type+'_votes'+content_id).html());
						var new_score = curr_score*curr_votes+score;
						var new_votes = curr_votes+1;

						$('#rating_'+type+'_score'+content_id).html((new_score/new_votes).toFixed(2));
						$('#rating_'+type+'_votes'+content_id).html(new_votes);

						ratingstar_reset(type, content_id, 1);

						$('#rating_'+type+'_progress'+content_id).hide();
						return true;
					}
				}
			}

		}
	);
}

// reports
function submit_report(type, member_id, content_id, noreason)
{
	var reason = $('#report_'+type+'_reason'+content_id).val();
	if ( !reason ) { alert(noreason); return; }

	$('#report_'+type+'_progress'+content_id).show();

	$.post(virpath+'index.php?hp=1&m=report', {'type':type,'reason':reason,'member_id':member_id,'content_id':content_id},
		function(response) {
			var response = response.split("\n");
			if ( response.length == 2 )
			{
				if ( response[0] == 'ok' && response[1] )
				{
					$('#report_'+type+'_progress'+content_id).hide();
					$('#report_'+type+'_response'+content_id).html('<div class="response">' + response[1] + '</div>');
					setTimeout(function(){
						$('#report_'+type+'_response'+content_id).animate({ opacity: "hide" }, "slow");
					}, 2500);
					return true;
				}
			}

		}
	);
}

// send wink
function send_wink(member_id, message_id)
{
	window.location = virpath+'index.php?m=account_messages&p=quickmessage&id='+member_id+'&sid='+message_id;
}

// polls
function submit_poll(poll_id, answer_id)
{
	$('#poll_'+poll_id+'_progress').show();

	$.post(virpath+'index.php?hp=1&m=vote', {'poll_id':poll_id,'answer_id':answer_id},
		function(response) {
			var response = response.split("\n");
			if ( response.length == 3 )
			{
				if ( response[0] == 'ok' && response[1] )
				{
					$('#poll_'+poll_id+'_results').html(response[1]);
					$('#poll_'+poll_id+'_results_wrap').show();
					var votes = response[2].split(",");
					for ( var i = 0, totalvotes = votes.length; i < totalvotes; i++ ) {
						var counters = votes[i].split("=");
						if ( counters.length == 2 )
						{
							$('#poll_'+poll_id+'_results_'+counters[0]).html('['+counters[1]+']');
							$('#poll_'+poll_id+'_results_'+counters[0]).css('display', 'inline');
							$('#poll_'+poll_id+'_checkbox_'+counters[0]).hide();
							$('#poll_'+poll_id+'_checkbox_'+counters[0]+'_obj').attr('disabled','disabled');
						}
					}
					$('#poll_'+poll_id+'_progress').hide();
					return true;
				}
			}
			else if ( response.length == 2 )
			{
				if ( response[0] == 'ok' && response[1] )
				{
					$('#poll_'+poll_id+'_results').html(response[1]);
					$('#poll_'+poll_id+'_results_wrap').show();
					for ( var i = 0; $('#poll_'+poll_id+'_checkbox_'+i) != null; i++ ) {
						$('#poll_'+poll_id+'_checkbox_'+counters[0]).hide();
						$('#poll_'+poll_id+'_checkbox_'+counters[0]+'_obj').attr('disabled','disabled');
					}
					$('#poll_'+poll_id+'_progress').hide();
					return true;
				}
			}
		}
	);
}

// vote icons
function ratingstar_toggle(type, content_id, score)
{
	for ( var i = 1; i <= 5; i++ ) {
		if ( i <= score ) {
			if ( $('#ratingstar'+content_id+'__'+i).hasClass("over") == false ) {
				$('#ratingstar'+content_id+'__'+i).addClass("over");
			}
		}
		else {
			$('#ratingstar'+content_id+'__'+i).removeClass("over");
		}
	}
}

function ratingstar_reset(type, content_id, lock)
{
	var score = Math.round($('#rating_'+type+'_score'+content_id).html());
	if ( score < 0 || score > 5 ) score = 0;
	for ( var i = 1; i <= 5; i++ ) {
		if ( i <= score ) {
			if ( $('#ratingstar'+content_id+'__'+i).hasClass("over") == false ) {
				$('#ratingstar'+content_id+'__'+i).addClass("over");
			}
		}
		else {
			$('#ratingstar'+content_id+'__'+i).removeClass("over");
		}
		if ( typeof(lock) != 'undefined' && lock ) {
			$('#ratingstar'+content_id+'__'+i).attr("onclick", "return false;");
			$('#ratingstar'+content_id+'__'+i).attr("onmouseover", "return false;");
			$('#ratingstar'+content_id+'__'+i).attr("disabled", "disabled");
		}
	}
}

// fetch contacts
function fetch_contacts(lng_submit, lng_checker, lng_select_label, lng_empty_details, lng_invalid_details)
{
	if ( !$('#mem_username').val() || !$('#mem_password').val() ) {
		$('#emailnfo').html('<br>'+lng_empty_details);
		return;
	}

	$('#invite_progress').show();
	$('#serverstatus').attr("disabled", "true");
	$('#emailnfo').html('');
	$.post(virpath+'index.php?m=invitefriends&p=fetch_contacts', {'emailtype':emailtype,'username':$('#mem_username').val(),'password':$('#mem_password').val()},
		function(response) {
			var response = response.split("\n");
			if ( response.length > 1 )
			{
				var str = '';
				for ( i in response ) {
					if ( response[i] != 'ok' ) {
						email = (response[i]).split('|||');
						if ( typeof(email) != 'undefined' && email.length == 2 ) {
							str += '<label><input type="checkbox" name="emails[]" value="'+email[0]+"|||"+email[1]+'" /> '+email[0]+' ('+email[1]+')</label><br>';
						}
					}
				}
				if ( str ) {
					str += '<br><input class="submit" name="submit" value="'+lng_submit+'" type="submit">';
					str = '<br><label><input type="checkbox" name="check_all_messages" value="0" onclick="toggleMessages(this.form, this.checked)" /> '+lng_checker+'</label><br>' + str;
					$('#emailnfo').html('<br><span>'+lng_select_label+':</span>'+str);
				}
				else {
					$('#emailnfo').html('<br>'+lng_invalid_details);
				}
			}
			else if ( response == 'empty_details' )
			{
				$('#emailnfo').html('<br>'+lng_empty_details);
			}
			else
			{
				$('#emailnfo').html('<br>'+lng_invalid_details);
			}
			$('#invite_progress').hide();
			$('#serverstatus').removeAttr('disabled');
		}
	);
}

function contacts_switchmail(type)
{
	emailtype = type;
	switch (type)
	{
		case 'custom':
			$('#field_email_custom').show();
			$('#field_email_public').hide();
			break;
		case 'aol':
			$('#field_email_public').show();
			$('#field_email_custom').hide();
			$('#emailext').html('');
			break;
		default:
			$('#field_email_public').show();
			$('#field_email_custom').hide();
			$('#emailext').html('@'+type+'.com');
			break;
	}
	$('#mem_username').val('')
	$('#mem_password').val('')
}

// check username
function checkusername(username)
{
	$.post(virpath+'index.php?hp=1&m=checkusername', {'username':username},
		function(response) {
			var response = trim(response);
			response = response.split("\n");
			if ( response.length == 2 )
			{
				$('#field_username_status').html(response[1]);
				$('#field_username_status').removeClass('true');
				$('#field_username_status').removeClass('false');
				if ( response[0] == 'ok' ) {
					$('#field_username_status').addClass('true');
				}
				else {
					$('#field_username_status').addClass('false');
				}
				$('#field_username_status').show(300);
			}

		}
	);
}

// toggles
function row_toggle(name)
{
    for (var i = 0; document.getElementById(name+'_'+i) != null;  i++)
    {
        if (document.getElementById(name+'_'+i).style.display == "none")
            $('#'+name+'_'+i).show();
        else
            $('#'+name+'_'+i).hide();
    }
}

// switches
function row_switch(name)
{
    $('#'+active_tab).hide();
    $('#'+name).show();
    active_tab = name;
}

// tabs
var active_tab = 0;
var active_tab_first = 1;
function switch_tabs(prefix, new_tab, first)
{
	if ( typeof(first) != 'undefined' ) {
		if ( active_tab_first == 1 ) {
			$('#'+prefix + '_' + new_tab + '_content').show();
			$('#'+prefix + '_' + new_tab + '_tab').addClass("active");
			active_tab = new_tab;
			active_tab_first = 0;
		}
	}
	else if ( active_tab != new_tab ) {
		$('#'+prefix + '_' + active_tab + '_content').hide(300);
		$('#'+prefix + '_' + active_tab + '_tab').removeClass("active");

		$('#'+prefix + '_' + new_tab + '_content').show(300);
		$('#'+prefix + '_' + new_tab + '_tab').addClass("active");
		active_tab = new_tab;
	}
}

function toggle_popup(objid,objstart){
	if($("#"+objid).css("display")!="none"){
		$("#"+objid).fadeOut("fast");
	}else{
		pstart=$(objstart).offset();
		$("#"+objid).fadeIn("fast");
		$("#"+objid).css("top", (pstart.top+$(objstart).height())+"px");
		$("#"+objid).css("left", pstart.left+"px");
	}
}

function showhide_field(name, show, plain)
{
    if ( $('#'+name).css("display") == "none" && (show == undefined || show == '') || show == 1 )
    {
    	if ( plain == undefined ) {
        	$('#'+name).fadeIn("fast");
		}
		else {
    		$('#'+name).show();
		}
    }
    else
    {
    	if ( plain == undefined ) {
        	$('#'+name).fadeOut("fast");
		}
		else {
    		$('#'+name).hide();
		}
    }
}

var events_ids = [];
function eventScroll(day, total)
{
	if ( typeof(events_ids[day]) == 'undefined' ) {
		events_ids[day] = 0;
	}
	if ( total == 1 ) {
		return;
	}
	var id = (events_ids[day] == (total - 1)) ? 0 : events_ids[day] + 1;
	events_ids[day] = id;
    for (var i = 0; document.getElementById('event_' + day + '_' + i) != null;  i++)
    {
        if ( i != id ) {
            $('#event_' + day + '_' + i).hide();
		}
    }
    $('#event_' + day + '_' + id).show();
}

// misc
function confirmLink(question, url)
{
    var is_confirmed = confirm(question);

    if (is_confirmed && url != '')
        window.location = url;

    return is_confirmed;
}

function confirmForm(question, form)
{
    var is_confirmed = confirm(question);

    if (is_confirmed && form != '')
        eval('document.' + form + '.submit()');

    return is_confirmed;
}

function toggleMessages(form, check)
{
    for (var i = 0; i < form.elements.length; i++)
    {
        if (form.elements[i].type == 'checkbox')
        {
            form.elements[i].checked = check;
        }
    }
}

function toggleItems(form, check)
{
    for (var i = 0; i < form.elements.length; i++)
    {
        if (form.elements[i].type == 'checkbox')
        {
            form.elements[i].checked = check;
        }
    }
}

function stylizeBooleanBox(prefix, boxid)
{
	var options = document.getElementById(prefix + boxid);
	for ( var i = 0, length = options.length; i < length; i++ )
	{
		options[i].style.background = ( options[i].value == 1 ) ? '#DEFAE0' : '#FBDDDD';
		if ( options[i].value == 1 && options[i].selected )
			document.getElementById(prefix + boxid).style.background = '#DEFAE0';
		else if ( options[i].value == 0 && options[i].selected )
			document.getElementById(prefix + boxid).style.background = '#FBDDDD';
	}
}

// toolpics
$.fn.ToolTip = function(customclass)
{
	this.mouseover(
		function(e)
		{
			if((!this.title && !this.alt) && !this.tooltipset) return;
			var mouseX = e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft : 0);
			var mouseY = e.pageY || (e.clientY ? e.clientY + document.body.scrollTop : 0);
			mouseX += 10;
			mouseY += 10;
			if(!this.tooltipdiv)
			{
				var div = document.createElement("div");
				this.tooltipdiv = div;
				$(div).addClass(customclass || 'tooltip');
				$(div).html((this.title || this.alt));
				this.title = "";
				this.alt = "";
				$("body").append(div);
				this.tooltipset = true;
			}
			$(this.tooltipdiv).fadeIn("fast").css({left: mouseX + "px", top: mouseY + 3 + "px"});
		}
	).mousemove(
		function(e)
		{
			if(!this.tooltipset) return;
			var mouseX = e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft : 0);
			var mouseY = e.pageY || (e.clientY ? e.clientY + document.body.scrollTop : 0);
			mouseX += 10;
			mouseY += 10;
			$(this.tooltipdiv).css({left: mouseX + "px", top: mouseY + 3 + "px"});
		}
	).mouseout(
		function()
		{
			if(this.tooltipdiv)
			{
				$(this.tooltipdiv).fadeOut("fast");
			}
		}
	);
	return this;
}

function selectSmiley(smiley_id, textbox)
{
	var val = $('#'+textbox).val();
	val = val + '' + smilies[smiley_id]['shortcut'];
	if($('#'+textbox).attr("disabled")==undefined || !$('#'+textbox).attr("disabled")){
		$('#'+textbox).val(val);
	}
}

//------------------------------------------------
// Chat
//------------------------------------------------
var chatwincurr = 0;
var autocheck = 0;
var autodelay = 8;
var virpath = '';
chatwins = new Array();

function checkChat(path,check,delay)
{
    virpath = path;
    autocheck = check;
    autodelay = delay;
    checkChatText();
}

//function checkChatText() {
//	$.post(virpath+'chat.php?p=check', {},
//		function(member_id) {
//			member_id=parseInt(member_id);
//  			if ( member_id > 0 ) {
//		        if(!openChatWindow(member_id)){
//		        	setTimeout('checkChatText()', (autodelay*1000));
//		        }
//			}
//			else {
//			    if ( autocheck ) {
//			        setTimeout('checkChatText()', (autodelay*1000));
//				}
//			}
//		}
//	);
////	refresh_status();
//}
var check_chat_text_timer=null;
function checkChatText(check_once) {

	jQuery.post(
			virpath+"ajax.php",
			{
				"action":"check_chat"
			},
			function(data,status){
				if(status=="success"){
					response=eval(data)[0];
					if(response.result){
						if(response.chat_members.length>0){
							for(counter=0;counter<response.chat_members.length;counter++){
								openChatWindow(response.chat_members[counter]);
							}
						}
						try{
							set_chat_status(response);
						}catch(e){}

					}
					if(response.status=="notloggedin"){
						window.location.reload();
					}
					check_chat_text_timer=setTimeout('checkChatText()', (autodelay*1000));
				}
			},
			"text"
	)
	if(arguments.length<1){
//		check_chat_text_timer=setTimeout('checkChatText()', (autodelay*1000));
	}

}

function openChatWindow(member_id) {
    if (member_id > 0 && (typeof(chatwins['chat' + member_id]) != "object"  ||  chatwins['chat' + member_id].closed)) {
        chatwins['chat' + member_id] = window.open(virpath + 'index.php?m=account_chat&p=request&id=' + member_id, 'chat' + member_id, 'width=400,height=459,resizable=yes,scrollbars=no,toolbar=no,location=no,status=no,menubar=no');
        if ( chatwins['chat' + member_id] && chatwins['chat' + member_id].open){
        	chatwins['chat' + member_id].focus();
        	return true;
        }
		else{
			temp=$.cookies.get()
			if(temp.disable_popup_blocker_alert==undefined || temp.disable_popup_blocker_alert!="true"){
				alert('Could not open a chat window. Please disable your popup blocker.');
				$.cookies.set("disable_popup_blocker_alert","true");
			}
			return false
		}
    }
    return false;
}

function trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}

function restoreWindow(info){
//	alert(info.left+":"+info.top);
	window.moveTo(info.left,info.top);
	window.focus();
//	window.blur();
//	aaa=if0.showModelessDialog("javascript:alert();window.close();","","status:no;resizable:no;help:no;dialogHeight:30px;dialogWidth:40px;");

//	window.getAttention();
//	window.focus();
//	window.blur();
}

function save_search()
{
	var name = $('#field_search_save').val();
	var hash = $('#field_hash').val();

	if(name != '' && hash != '')
	{
		$('#save_search_progress').show();
		$('#save_search_submit').attr({disabled: "disabled"});

		$.post(virpath+'index.php?hp=1&m=searches&p=save', {'name':name,'s':hash},
			function(response) {
				var response = response.split("\n");
				if ( response.length > 0 )
				{
					if ( response[0] == 'ok' && response[1] )
					{
						$('#save_search_progress').hide();
						$('#save_search_response').html(response[1]);

						if ( response[2] )
						{
							setTimeout(function(){
								$('#div_save_search' ).animate({ opacity: "hide" }, "slow");
							}, 2000);
						}
						return true;
					}
				}
			}
		);
	}
}

// comments pagination
function get_comments_page(type, member_id, content_id, page)
{
	$('#get_comments_progress').show();

	$.post(virpath+'index.php?hp=1&m=comments', {'type':type,'member_id':member_id,'content_id':content_id,'page':page},
		function(response) {
			var response = response.split("|");
			if ( response.length == 2 )
			{
				if ( response[0] == 'ok' && response[1] )
				{
					$('#get_comments_progress').hide();
					$('#comments_page').html(response[1]);
					return true;
				}
			}

		}
	);
}

//$(document).ready(
//	function(){
//		status_timer=setInterval(refresh_status,10*60*1000);	// refresh every 10 mins
//	}
//);
//
//function refresh_status(){
//	$.post(
//			"/",
//			{
//				"refresh_status":1
//			},
//			function(data,status){
//				if(status=="success"){
//				}
//			},
//			"text"
//	);
//}


function getImgSize(imgSrc){
	var newImg = new Image();
	newImg.src = imgSrc;
	return {"height":newImg.height,"width":newImg.width};
}


var previewSize={
					"width":100,
					"height":100
					};
var sourceImageSize={
					"width":100,
					"height":100
					};
var sourceRawImageSize={
					"width":100,
					"height":100
					}
var imageLimitSize={
					"width":800,
					"height":650
					};

var imageSelectSize={
					"width":0,
					"height":0,
					"x1":0,
					"y1":0,
					"x2":0,
					"y2":0
}

function preview(img, selection)
{
	var scaleX = previewSize.width / (selection.width || 1);
	var scaleY = previewSize.height / (selection.height || 1);

	$('#preview_image').css({
		"width": Math.round(scaleX * sourceImageSize.width) + 'px',
		"height": Math.round(scaleY * sourceImageSize.height) + 'px',
		"marginLeft": '-' + Math.round(scaleX * selection.x1) + 'px',
		"marginTop": '-' + Math.round(scaleY * selection.y1) + 'px'
	});
	$("#param").html("");
}

var popup_fetch=new Object();
function get_popup(popupname,callback,parent){
	if($("#"+popupname).length<1 && !popup_fetch[popupname]){
		jQuery.post(
				"/ajax.php",
				{
					"action":"get_popup",
					"popupname":popupname
				},
				function(data,status){
					if(status=="success"){
						response=eval(data)[0];
						if(parent){

							if(popupname=="picture_overlay"){
								$(parent).prepend(response.attach.template);
							}else{
								$(parent).append(response.attach.template);
							}
						}else{
							$(document.body).append(response.attach.template);
						}
						if(callback){
							callback(response);
						}
					}
				},
				"text"
			);
		popup_fetch[popupname]=true;
		return false;
	}
	callback();
	return true;
}

var picture_override="";
var picture_overide_action="";
function callback_popup_edit_picture(response){
	if(response!=undefined){
		$("#source_image").attr("src",response.attach.user_image);
	}

	if(picture_override!=""){
		$("#source_image").attr("src",picture_override);
	}


	$("#source_image").ready(
			function(){
				sourceImageSize=getImgSize($("#source_image").attr("src"));
				if($("#source_image").attr("src")=="/media/uploads/"){
					if(confirm("You have no photo to edit, upload one?")){
						window.location.href="/account/photo/";
					}
					return false;
				}

//				alert(sourceImageSize.width+"x"+sourceImageSize.height);

				if(sourceImageSize.width*sourceImageSize.height<1){
					setTimeout(function(){callback_popup_edit_picture(response)},500);
					return false;
				}

				sourceRawImageSize=getImgSize($("#source_image").attr("src"));
				adj= (imageLimitSize.width/sourceImageSize.width)>(imageLimitSize.height/sourceImageSize.height)?"width":"height";
				$("#source_image").removeAttr("height");
				$("#source_image").removeAttr("width");

				if(adj=="width"){
					if(imageLimitSize.width<sourceImageSize.width){
						$("#source_image").attr("width",imageLimitSize.width);

						sourceImageSize.width=imageLimitSize.width;
						sourceImageSize.height=sourceRawImageSize.height*(imageLimitSize.width/sourceRawImageSize.width);

					}
				}else{
					if(imageLimitSize.height<sourceImageSize.height){
						$("#source_image").attr("height",imageLimitSize.height);

						sourceImageSize.height=imageLimitSize.height;
						sourceImageSize.width=sourceRawImageSize.width*(imageLimitSize.height/sourceRawImageSize.height);
					}
				}
				initpos1={
						"left":(sourceImageSize.width-100)/2,
						"top":(sourceImageSize.height-100)/2
						}
				initpos2={
						"left":(sourceImageSize.width-100)/2+100,
						"top":(sourceImageSize.height-100)/2+100
						}

				if(picture_override!=""){
					dialog_position={
	//						"top":$(document).scrollTop()+($(document).height()-$("#dialog_edit_picture").height())/2,
							"top":150,
							"left":$(document).scrollLeft()+($(document).width()-$("#dialog_edit_picture").width())/2
					}
				}else{
					dialog_position={
	//						"top":$(document).scrollTop()+($(document).height()-$("#dialog_edit_picture").height())/2,
							"top":$(".user_side").offset().top,
							"left":$(document).scrollLeft()+($(document).width()-$("#dialog_edit_picture").width())/2
					}
				}


				$("#dialog_edit_picture").css("top",dialog_position.top+"px");
				$("#dialog_edit_picture").css("left",dialog_position.left+"px");
				$("#dialog_edit_picture").css("width",(sourceImageSize.width+22)+"px");
				$("#dialog_edit_picture").css("text-align","left");
				$("#dialog_edit_picture").css("z-index","100");
				$("#dialog_edit_picture").css("display","block");

				//set preview frame
				$("#preview_image_frame").css("height",previewSize.height+"px");
				$("#preview_image_frame").css("width",previewSize.width+"px");

				//start edit function (region pick)


				//bind event on cancle button
				if($("#dialog_edit_picture").attr("attr_bind")==undefined || !$("#dialog_edit_picture").attr("attr_bind")){
					$('#source_image').imgAreaSelect(
												{
													"onSelectChange":preview,
													"handles":false,
													"minHeight":100,
													"minWidth":100,
													"x1":initpos1.left,
													"y1":initpos1.top,
													"x2":initpos2.left,
													"y2":initpos2.top,
													"aspectRatio":"1:1",
													"onSelectChange":onImageSelect,
													"onSelectStart":onImageSelect,
													"onSelectEnd":onImageSelect
												}
											);
					imageSelectSize={
						"width":100,
						"height":100,
						"x1":initpos1.left,
						"y1":initpos1.top,
						"x2":initpos2.left,
						"y2":initpos2.top

					};

					$("#dialog_edit_picture input[type=button][id=cancel]").click(
							function(){
								$("#source_image").imgAreaSelect({"hide":true});
								$("#dialog_edit_picture").css("display","none");
							}
					);
					$("#dialog_edit_picture input[type=button][id=save]").click(
							function(){
								$("#dialog_edit_picture input[type=button][id=save]").attr("disabled","disabled");
								save_resize_image();
							}
					);
					$("#dialog_edit_picture").attr("attr_bind","true");
				}else{

					if(picture_override!=""){
						$('#source_image').imgAreaSelect(
								{
									"onSelectChange":preview,
									"handles":false,
									"minHeight":100,
									"minWidth":100,
									"x1":initpos1.left,
									"y1":initpos1.top,
									"x2":initpos2.left,
									"y2":initpos2.top,
									"aspectRatio":"1:1",
									"onSelectChange":onImageSelect,
									"onSelectStart":onImageSelect,
									"onSelectEnd":onImageSelect
								}
							);
					}else{
						$('#source_image').imgAreaSelect(
								{
									"hide":false,
									"handles":false,
									"minHeight":100,
									"minWidth":100,
									"x1":imageSelectSize.x1,
									"y1":imageSelectSize.y1,
									"x2":imageSelectSize.x2,
									"y2":imageSelectSize.y2,
									"aspectRatio":"1:1",
									"onSelectChange":onImageSelect,
									"onSelectStart":onImageSelect,
									"onSelectEnd":onImageSelect
								}
							);
					}
				}

			}
	);
}

function save_resize_image(){
	check_total=0;
	for(name in imageSelectSize){
		check_total+=parseInt(imageSelectSize[name]);
		if(imageSelectSize[name]==NaN){
			alert("Please pick an area from the picture");
			$("#dialog_edit_picture input[type=button][id=save]").removeAttr("disabled");
			return false;
		}
	}
	if(check_total<400){
		alert("Please pick an area from the picture");
		$("#dialog_edit_picture input[type=button][id=save]").removeAttr("disabled");
		return false;
	}

	ratio=sourceRawImageSize.width/sourceImageSize.width;


	imageWidth=sourceRawImageSize.width;
	imageHeight=sourceRawImageSize.height;
	selectX=imageSelectSize.x1*ratio;
	selectY=imageSelectSize.y1*ratio;
	selectWidth=imageSelectSize.width*ratio;
	selectHeight=imageSelectSize.height*ratio;

	action="set_user_picture";
	if(picture_overide_action!=""){
		switch(picture_overide_action){
			case "update_pending_image":
				action="update_pending_image";
			break;
		}
	}

	jQuery.post(
					"/ajax.php",
					{
						"action":action,
						"file":$("#source_image").attr("src").split("?")[0],
						"imageWidth":imageWidth,
						"imageHeight":imageHeight,
						"selectX":selectX,
						"selectY":selectY,
						"selectWidth":selectWidth,
						"selectHeight":selectHeight
					},
					function(data,status){
						if(status=="success"){
							response=eval(data)[0];
							if(response.result){
								window.location.reload();
//								alert("Succeed! Please refresh the page");
								$("img").each(
										function(){
											try{
												ori=$(this).attr("src");
												rnd=Math.ceil(Math.random() * 100);
												$(this).attr("src",ori+"?"+rnd);
											}catch(e){}
											$("#source_image").imgAreaSelect({"hide":true});
											$("#dialog_edit_picture").css("display","none");
										}
								);
							}
							$("#dialog_edit_picture input[type=button][id=save]").attr("disabled","");
						}
					},
					"text"
			);
}

var picture_overlay_displaying=false;
var picture_overlay_focused=false;
var picture_overlay_action_displaying=false;
function callback_position_picture_overlay(response){
	$("#picture_overlay").ready(
		function(){
			jq_picture_overlay=$("#picture_overlay");
			if(jq_picture_overlay.length<1){
				return;
			}
			jq_picture_overlay.css("display","block");

			if(hide_picture_options.edit){
				$("#picture_overlay_actions").find("a:contains(Edit Photo)~br").remove();
				$("#picture_overlay_actions").find("a:contains(Edit Photo)").remove();
			}
			if(hide_picture_options.del){
				$("#picture_overlay_actions").find("a:contains(Delete Photo)~br").remove();
				$("#picture_overlay_actions").find("a:contains(Delete Photo)").remove();
			}

			if(jq_picture_overlay.attr("event_set")==undefined || !jq_picture_overlay.attr("event_set")){
				jq_picture_overlay.click(
							function(){
								$("#picture_overlay_actions").css("display","block");
								$(this).css("display","none");
							}
				);
				$(".user_img_editbox_top").click(
					function(){
						$("#picture_overlay_actions").css("display","none");
						$("#picture_overlay").css("display","block");
					}
				);
				jq_picture_overlay.attr("event_set","true");
			}
		}
	);
}

var hide_picture_options={
		"upload":false,
		"edit":false,
		"del":false
}
function bind_picture_edit_layout(bindObj){
	$(bindObj).ready(
			function(){
					imagearea=$(bindObj);
					if(imagearea.find("img").attr("src")!=undefined && imagearea.find("img").attr("src").search("template")>=0){
						hide_picture_options.edit=true;
						hide_picture_options.del=true;
					}
					imagearea.mouseover(
						function(event){
							if($("#picture_overlay").length<1){
								get_popup('picture_overlay',callback_position_picture_overlay,$("#image_bind"));
							}else{
								if($("#picture_overlay_actions").css("display")=="none"){
									$("#picture_overlay").css("display","block");
								}
							}

						}
					);
					imagearea.mouseleave(
						function(){
							$("#picture_overlay").css("display","none");
						}
					);
					$(".container").click(
						function(event){
							if(event.target==this){
								$("#picture_overlay_actions").css("display","none");
							}
						}
					);
			}
	);
}


function onImageSelect(img, selection){
		imageSelectSize=selection;
}

function delete_account_picture(){
	if(!confirm("Are you sure to delete the photo?")){
		return false;
	}
	jQuery.post(
				"/ajax.php",
				{
					"action":"delete_account_picture"
				},
				function(data,status){
					if(status=="success"){
						window.location="/account/photo/";
//						window.location.reload();
					}
				},
				"text"
			);
}


function decode_query(){
	returnValue={};
	returnValue.params={};
	temp=window.location.href.split("?");
	returnValue.querypage=temp.shift();

	array_str_param=temp.join("?").split("&");


	for(counter=0;counter<array_str_param.length;counter++){
		param_pair=array_str_param[counter].split("=");
		key=param_pair.shift();
		returnValue.params[key]=param_pair.join("=");
	}
	return returnValue;

}

function encode_query(queryvar){
	temp=new Array();
	for(name in queryvar.params){
		if(name!=""){
			temp.push(name+"="+queryvar.params[name]);
		}
	}
	return queryvar.querypage+"?"+temp.join("&");
}

function simple_sort(sortfieldname){
	query=decode_query();
	if(query.params.sort==undefined){
		query.params.sort=sortfieldname;
		query.params.order="asc";
	}else{
		if(query.params.sort==sortfieldname){
			query.params.order=query.params.order=="asc"?"desc":"asc";
		}else{
			query.params.sort=sortfieldname;
			query.params.order="asc";
		}
	}
	window.location.href=encode_query(query);
}

function account_edit_id(show_id){
	show_id=show_id;
	if(arguments.length<1){
		show_id="true";
	}
	if(show_id!="true"){
		show_id="false";
	}

	jQuery.post(
				"/ajax.php",
				{
					"action":"account_edit_id",
					"set_edit_id":show_id
				},
				function(data,status){
					if(status=="success"){
						response=eval(data)[0];
						if(response.result){
							window.location.href="/account/profile/";
						}
					}
				},
				"text"
			);
	return false;
}

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

function change_list_view(page, type){
	jQuery.post(
		"/ajax.php",
		{
			"action":"change_list_view",
			"page":page,
			"type":type
		},
		function(data,status){
			if(status=="success"){
				response=eval(data)[0];
				if(response.result){
					window.location.reload();
				}
			}
		},
		"text"
	);
}

function set_account_view(view){
	jQuery.post(
				"/ajax.php",
				{
					"action":"set_account_view",
					"view":view
				},
				function(data,status){
					if(status=="success"){
						response=eval(data)[0];
						if(response.result){
							window.location.href="/account/profile/";
						}
					}
				},
				"text"
	);
	return false;
}