var faces = new Array();
//var faces = [{"x":"6","y":"52","w":"107","h":"107","c":"65.38","yy":"0","p":"0","r":"0","image":"http:\/\/starsinyou.neon.loc\/\/uploads\/1274240143060028800_0.jpg"},{"x":"12","y":"262","w":"105","h":"105","c":"73.37","yy":"0","p":"0","r":"0","image":"http:\/\/starsinyou.neon.loc\/\/uploads\/1274240143060028800_1.jpg"},{"x":"333","y":"50","w":"103","h":"103","c":"84.51","yy":"0","p":"0","r":"-8","image":"http:\/\/starsinyou.neon.loc\/\/uploads\/1274240143060028800_2.jpg"},{"x":"491","y":"57","w":"101","h":"101","c":"63.98","yy":"0","p":"0","r":"0","image":"http:\/\/starsinyou.neon.loc\/\/uploads\/1274240143060028800_3.jpg"},{"x":"265","y":"264","w":"97","h":"97","c":"70.86","yy":"0","p":"0","r":"0","image":"http:\/\/starsinyou.neon.loc\/\/uploads\/1274240143060028800_4.jpg"},{"x":"185","y":"55","w":"97","h":"97","c":"73.33","yy":"0","p":"0","r":"0","image":"http:\/\/starsinyou.neon.loc\/\/uploads\/1274240143060028800_5.jpg"},{"x":"130","y":"256","w":"92","h":"92","c":"58.67","yy":"0","p":"0","r":"0","image":"http:\/\/starsinyou.neon.loc\/\/uploads\/1274240143060028800_6.jpg"},{"x":"513","y":"264","w":"87","h":"87","c":"60.66","yy":"0","p":"0","r":"0","image":"http:\/\/starsinyou.neon.loc\/\/uploads\/1274240143060028800_7.jpg"}];
//var faces = [{"x":"6","y":"52","w":"107","h":"107","c":"65.38","yy":"0","p":"0","r":"0","image":"http:\/\/api.starsinyou.com\/downloads\/1279018072062290600_0.jpg"},{"x":"12","y":"262","w":"105","h":"105","c":"73.37","yy":"0","p":"0","r":"0","image":"http:\/\/api.starsinyou.com\/downloads\/1279018072062290600_1.jpg"},{"x":"333","y":"50","w":"103","h":"103","c":"84.51","yy":"0","p":"0","r":"-8","image":"http:\/\/api.starsinyou.com\/downloads\/1279018072062290600_2.jpg"},{"x":"491","y":"57","w":"101","h":"101","c":"63.98","yy":"0","p":"0","r":"0","image":"http:\/\/api.starsinyou.com\/downloads\/1279018072062290600_3.jpg"},{"x":"265","y":"264","w":"97","h":"97","c":"70.86","yy":"0","p":"0","r":"0","image":"http:\/\/api.starsinyou.com\/downloads\/1279018072062290600_4.jpg"},{"x":"185","y":"55","w":"97","h":"97","c":"73.33","yy":"0","p":"0","r":"0","image":"http:\/\/api.starsinyou.com\/downloads\/1279018072062290600_5.jpg"},{"x":"130","y":"256","w":"92","h":"92","c":"58.67","yy":"0","p":"0","r":"0","image":"http:\/\/api.starsinyou.com\/downloads\/1279018072062290600_6.jpg"},{"x":"513","y":"264","w":"87","h":"87","c":"60.66","yy":"0","p":"0","r":"0","image":"http:\/\/api.starsinyou.com\/downloads\/1279018072062290600_7.jpg"}];
var matches = new Array();
//var matches = [{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/31719","name":"ellen adarna","score":"180","id":"4045","tmplId":"31719"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/29296","name":"elisha cuthbert","score":"40","id":"994","tmplId":"29296"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/7355","name":"donald trump","score":"34","id":"908","tmplId":"7355"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/40961","name":"Dita Von Teese","score":"33","id":"4841","tmplId":"40961"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/5885","name":"claire forlani","score":"32","id":"698","tmplId":"5885"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/18027","name":"lenny kravitz","score":"32","id":"2311","tmplId":"18027"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/42369","name":"Katja Riemann","score":"32","id":"4963","tmplId":"42369"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/4099","name":"Bonnie Pink","score":"31","id":"464","tmplId":"4099"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/5865","name":"claire danes","score":"31","id":"697","tmplId":"5865"},{"image":"http:\/\/api.starsinyou.com\/image\/get\/celeb\/16737","name":"katherine hepburn","score":"31","id":"2129","tmplId":"16737"}];
var myMatches = new Array();
var selected;
var selectedCeleb;
var userGender = '';
var currentWindow = null;
var previousWindow = '';
var valignVal = 0;
var centerWidth;
var hasTask = false;

(function ($) {
// VERTICALLY ALIGN FUNCTION
$.fn.vAlign = function() {
	return this.each(function(i){
	var ah = $(this).height();
	var ph = $(this).parent().height();
	var mh = (ph - ah) / 2;
//	console.log("ah="+ah+";ph="+ph+";mh="+mh);
	if(mh<0) {
		mh = 0;
	}
	$(this).css('margin-top', mh);
	valignVal = mh;
	});
};
})(jQuery);

$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});

(function() {
escape_re = /[#;&,\.\+\*~':"!\^\$\[\]\(\)=>|\/\\]/;
jQuery.escape = function jQuery$escape(s) {
  var left = s.split(escape_re, 1)[0];
  if (left == s) return s;
  return left + '\\' + 
    s.substr(left.length, 1) + 
    jQuery.escape(s.substr(left.length+1));
}
})();

function initializeEvents() {
	$(document).mouseup(function(e) {
		try {
			var targetId = $(e.target).attr('id');
			if((targetId == 'img_arrow') || (targetId == 'img_arrow_login') || (targetId == 'gritter-notice-wrapper')) {
				return;
			}
			else {
				var targetParent = $(e.target).parent().parent();
//				console.log(targetParent.attr('id')+" ... "+targetParent.attr('class'));
				if( (targetParent.attr('id') == 'gritter-notice-wrapper') || (targetParent.hasClass('gritter-item')) || (targetParent.hasClass('my-class'))) {
					return;
				}
			}
			if($("#signin_menu").hasClass('imopen')) {
				if(targetId != "login_link") {
					showLogIn(false, $('#signin_menu'), 300);
					return;
				}
			}
			if($("#register_menu").hasClass('imopen')) {
				if( (targetId != "register_link") && (targetId != "login_link")) {
					showLogIn(false, $('#register_menu'), 300);
					return;
				}
			}
			if($("#account_menu").hasClass('imopen')) {
				if(targetId != "account_link") {
					showLogIn(false, $('#account_menu'), 300);
					return;
				}
			}
			if($("#edit_account_menu").hasClass('imopen')) {
				if(targetId != "account_link") {
					showLogIn(false, $('#edit_account_menu'), 300);
					return;
				}
			}
			if($("#forgot_menu").hasClass('imopen')) {
				if((targetId != "login_link") && (targetId != "register_link") && (targetId != "linkRegister")) {
					showLogIn(false, $('#forgot_menu'), 300);
				}
			}
		}
		catch(err) {
			
		}
    });
    
    $('.ui-state-default').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);
	
	$("#img_arrow").click(function(event) {
		event.preventDefault();
		$('#error-content').hide();
		if($("#account_menu").hasClass('imopen')) {
			showLogIn(false, $('#account_menu'), 300);
		}
		else {
			if($("#edit_account_menu").hasClass('imopen')) {
				showLogIn(false, $('#edit_account_menu'), 300);
			}
			else {
				showLogIn(true, $('#account_menu'), 300);
			}
		}
	});
	$("#img_arrow_login").click(function(event) {
		event.preventDefault();
		$('#error-content').hide();
		if($("#signin_menu").hasClass('imopen')) {
			showLogIn(false, $('#signin_menu'), 300);
		}
		else {
			if($("#register_menu").hasClass('imopen')) {
				showLogIn(false, $('#register_menu'), 300);
			}
			else {
				showLogIn(true, $('#signin_menu'), 300);
			}
		}
	});
	$("#signin_cancel").click(function(event) {
		event.preventDefault();
		showLogIn(false, $('#signin_menu'), 300);
	});
	$("#register_cancel").click(function(event) {
		event.preventDefault();
		showLogIn(false, $('#register_menu'), 300);
	});
	$("#forgot_cancel").click(function(event) {
		event.preventDefault();
		showLogIn(false, $('#forgot_menu'), 300);
	});
	$("#edit_register_cancel").click(function() {
		showLogIn(false, $('#edit_account_menu'), 300, function(){
			showLogIn(true, $('#account_menu'), 300);
		});
	});
	$("#logout_link").click(function() {
		$('#form-logout').submit();
	});
	$(".signin").click(function(event) {
		$('#error-content').hide();
		if($("#signin_menu").hasClass('imopen')) {
			showLogIn(false, $('#signin_menu'), 300);
		}
		else {
			if($("#forgot_menu").hasClass('imopen')) {
				showLogIn(false, $('#forgot_menu'), 300, function() {
					showLogIn(true, $('#signin_menu'), 300);
				});
			}
			else {
				if($("#register_menu").hasClass('imopen')) {
					showLogIn(false, $('#register_menu'), 300, function() {
						showLogIn(true, $('#signin_menu'), 300);
					});
				}
				else {
					showLogIn(true, $('#signin_menu'), 300);
				}
			}
		}
    });
    $(".register").click(function() {
    	$('#error-content').hide();
		if($("#register_menu").hasClass('imopen')) {
			showLogIn(false, $('#register_menu'), 300);
		}
		else {
			if($("#forgot_menu").hasClass('imopen')) {
				showLogIn(false, $('#forgot_menu'), 300, function() {
					showLogIn(true, $('#register_menu'), 300);
				});
			}
			else {
				showLogIn(false, $('#signin_menu'), 300, function() {
					showLogIn(true, $('#register_menu'), 300);
				});
			}
		}
    });
    
	$(".account").click(function() {
    	if($("#account_menu").hasClass('imopen')) {
			showLogIn(false, $('#account_menu'), 300);
		}
		else {
			if($("#edit_account_menu").hasClass('imopen')) {
				showLogIn(false, $('#edit_account_menu'), 300, function(){
					showLogIn(true, $('#account_menu'), 300);
				});
			}
			else {
				showLogIn(true, $('#account_menu'), 300);
			}
		}
    });
    
    $(".edit_account").click(function() {
    	if($("#edit_account_menu").hasClass('imopen')) {
		}
		else {
			showLogIn(false, $('#account_menu'), 300, function() {
				showLogIn(true, $('#edit_account_menu'), 300);
				$('#edit-register-error-content').hide();
				fillUpForm(false);
			});
		}
    });
	$("fieldset").mouseup(function() {
		return false;
	});
	$("#gritter-notice-wrapper").mouseup(function() {
		return false;
	});
	
	$("#register_user").click(function(event) {
		var passwd = $('#txt_password').attr('value');
    	var cpasswd = $('#txt_confirm_password').attr('value');
    	var tEmail = $('#txt_email').attr('value');
    	
    	event.preventDefault();
    	if(checkEntries(tEmail, passwd, cpasswd, $('#register-error-content'), true)) {
    		$('#form-register').submit();
    	}
    });
    
    $("#btn_forgot_password").click(function(event) {
    	var tEmail = $('#txt_forgot_email').attr('value');
    	var tNick = $('#txt_forgot_nickname').attr('value');
    	var passwd='';
    	var cpasswd='';
    	
    	event.preventDefault();
    	if(checkEntries(tEmail, passwd, cpasswd, $('#forgot-error-content'), false)) {
    		$('#form-forgot').submit();
    	}
    });
    
    $("#edit_register_user").click(function(event) {
    	var passwd = $('#txt_password').attr('value');
    	var cpasswd = $('#txt_confirm_password').attr('value');
    	var tEmail = $('#txt_email').attr('value');
    	
    	event.preventDefault();
    	if(checkEntries(tEmail, passwd, cpasswd, $('#edit-register-error-content'), true)) {
    		$('#form-account').submit();
    	}
    });
    
    $("#signin_login").click(function(event) {
    	event.preventDefault();
    	var tEmail = $('#login_email').attr('value');
    	var tPasswd = $('#login_password').attr('value');
    	
    	if($.trim(tEmail) != "") {
    		if($.trim(tPasswd) != "") {
    			$('#form-signin').submit();
    		}
    		else {
//    			showMessage("Please input your password!", $('#error-content'));
				postIt("Please input your password!", "Error", 0);
    		}
    	}
    	else {
//    		showMessage("Please input your e-mail address!", $('#error-content'));
    		postIt("Please input your e-mail address!", "Error", 0);
    	}
    	return false;
    });
    
    $('#linkSignIn').click(function(){
    	$('#error-content').hide();
		if($("#signin_menu").hasClass('imopen')) {
//			showLogIn(false, $('#signin_menu'), 300);
		}
		else {
			showLogIn(false, $('#register_menu'), 300, function() {
				showLogIn(true, $('#signin_menu'), 300);
			});
		}
    });
    
    $('#linkRegister').click(function(){
    	$('#error-content').hide();
		if($("#register_menu").hasClass('imopen')) {
//			showLogIn(false, $('#signin_menu'), 300);
		}
		else {
			if($("#signin_menu").hasClass('imopen')) {
				showLogIn(false, $('#signin_menu'), 300, function() {
					showLogIn(true, $('#register_menu'), 300);
				});
			}
			else {
				if($("#forgot_menu").hasClass('imopen')) {
					showLogIn(false, $('#forgot_menu'), 300, function() {
						showLogIn(true, $('#register_menu'), 300);
					});
				}
				else {
					showLogIn(true, $('#register_menu'), 300);
				}
			}
		}
    });
    
    $('#forgot_link').click(function(){
    	$('#error-content').hide();
    	showLogIn(false, $('#signin_menu'), 300, function(){
    		showLogIn(true, $('#forgot_menu'), 300);
    	});
    });
    
    $('#facebook-img').load(function(){
    	var src = $('#facebook-img').attr('src');
    	if(src == "/images/loader.gif") {
    		$('#facebook-img').css('height', '15px');
    		$('#facebook-img').css('width', '40px');
    	}
    	else {
    		$('#uploaded_image').attr('src', src);
	    	var imgHeight = document.getElementById('facebook-img').offsetHeight;
	 		var imgWidth = document.getElementById('facebook-img').offsetWidth;
	 	
	 		var w = "width = "+imgWidth;
	 		var h = "height = "+imgHeight;
	 		
	 		if(imgHeight > imgWidth) {
	 			if(imgHeight >= 400) {
		 			$('#facebook-img').css('height', 400);
		 			$('#facebook-img').css('width', "auto");
	 			}
	 			else {
	 				$('#facebook-img').css('height', "auto");
		 			$('#facebook-img').css('width', "auto");
	 			}
	 		}
	 		else {
	 			if(imgWidth >= 580) {
		 			$('#facebook-img').css('width', 580);
		 			$('#facebook-img').css('height', "auto");
	 			}
	 			else {
	 				$('#facebook-img').css('width', "auto");
		 			$('#facebook-img').css('height', "auto");
	 			}
	 		}
	 		$('#txt-facebook-photo').attr('value', src);
    	}
 		$('#facebook-img').vAlign();
    });

    $('#uploaded_image').load(function() {
    	var src = $('#uploaded_image').attr('src');
    	if(src == "/images/blank.png") {
    		return;
    	}
//    	$('#subject_image').attr('src', src);
    	var imgHeight = document.getElementById('uploaded_image').offsetHeight;
 		var imgWidth = document.getElementById('uploaded_image').offsetWidth;
 	
 		var w = "width = "+imgWidth;
 		var h = "height = "+imgHeight;
 		if(imgHeight > imgWidth) {
 			if(imgHeight >= 400) {
	 			$('#uploaded_image').css('height', 440);
	 			$('#uploaded_image').css('width', "auto");
	 			
	 			$('#subject_image').css('height', 440);
	 			$('#subject_image').css('width', "auto");
	 			h = "height = "+imgHeight+ ' << = 440';
 			}
 			else {
 				$('#uploaded_image').css('height', "auto");
	 			$('#uploaded_image').css('width', "auto");
	 			
	 			$('#subject_image').css('height', "auto");
	 			$('#subject_image').css('width', "auto");
	 			h = "height = "+imgHeight+ ' << = auto';
 			}
 		}
 		else {
 			if(imgWidth >= 580) {
	 			$('#uploaded_image').css('width', 580);
	 			$('#uploaded_image').css('height', "auto");
	 			
	 			$('#subject_image').css('width', 580);
	 			$('#subject_image').css('height', "auto");
	 			w = "width = "+imgWidth + ' << = 580';
 			}
 			else {
 				$('#uploaded_image').css('width', "auto");
	 			$('#uploaded_image').css('height', "auto");
	 			
	 			$('#subject_image').css('width', "auto");
	 			$('#subject_image').css('height', "auto");
	 			w = "width = "+imgWidth + ' << = auto';
 			}
 		}

 		$('#container-get-started').hide();
    	$('#uploaded_image').vAlign();
    	$('#subject_image').css('margin-top', valignVal);
    });
    
    $('#btnUpload').click(function(event) {
    	event.preventDefault();
    });
    
    $('#get-started').click(function(event) {
    	$('uploadButton').trigger('click');
    });
    
    $('#btnTakePhoto').click(function(event) {
    	event.preventDefault();
    	showContainer($('#container-take-photo'), "dynamic");
    	$('#btnTakePhoto').hide();
    });
    
    $("#btnDetect").click(function(event) {
    	var imageSrc = $('#uploaded_image').attr('src');
		event.preventDefault();
		if((imageSrc) && imageSrc != '/images/blank.png') {
			$('#cmd_detect').attr('value', 'detect_faces');
    		$('#form-detect').submit();
		}
		else {
			showDialog("Please upload your photo first!", "Error", 0);
		}
	});	
	
	$(".btnStartOver").click(function(event) {
		event.preventDefault();
		$('#user_uploaded_image').attr('value', $('#uploaded_image').attr('src'));
		$('#cmd_start-over').attr('value', 'start_over');
		$('#form-start-over').submit();
	});	
	
	$("#btnResults").click(function(event) {
		event.preventDefault();
		faceMatch();
	});	
	
	$("#btnBack").click(function(event) {
		event.preventDefault();
		clearMatches();
		showContainer($('#container-detect'), "dynamic");
		showContainer($('#container-detect-left'), "dynamic-left");
		showContainer($('#container-detect-right'), "dynamic-right");
		$('.right_column_wrap1').show();
		//showContainer($('#container-detect'), "dynamic");
	});
	
	$("#btnSaveResults").click(function(event){
		event.preventDefault();
		saveResults();
	});
	
	$('#my_matches').click(function(event){
		$('#cmd-my-results').attr('value', 'get_my_results');
		$('#my-results-uid').attr('value', $('#user_uid').attr('value'));
		$('#form-my-results').submit();
	});
	
	$('#btnBackShowResults').click(function(event){
		if($('#'+currentWindow).hasClass('static-pages')) {
			maximize(true);
		}
		else {
			if(currentWindow == 'container-matches') {
				$('.right_column_wrap1').hide();
				if($('#user_uid').attr('value') == undefined) {
				}
				else {
					$('.xButton').css('display', 'block');
				}
			}
			else {
				$('.right_column_wrap1').show();
			}
		}
		showContainer($('#'+currentWindow), "dynamic");
		if(currentWindow == 'container-take-photo') {
			currentWindow = "container-main";
		}			
		showContainer($('#'+currentWindow+'-left'), "dynamic-left");
		showContainer($('#'+currentWindow+'-right'), "dynamic-right");
	});
	
	$('#btnShowMatches').click(function(event){
		if(getActiveWindow() == "container-celeb-info") {
			showContainer($('#'+previousWindow), "dynamic");
		}
		if($(this).text() == "show more matches") {
			$(this).text("show less matches");
			if($('#myMatchesContainer div.match_images.visible').size() > 5) {
				$('#myMatchesContainer').css('height', '100%');
				$('#myMatchesContainer').css('margin-top', '0px');
			}
		}
		else {
			$(this).text("show more matches");
			$('#myMatchesContainer').css('height', '50%');
			$('#myMatchesContainer').css('margin-top', '120px');
		}
	});
	
	$('#btnShowMatchesResults').click(function(event){
		if(getActiveWindow() == "container-celeb-info") {
			showContainer($('#'+previousWindow), "dynamic");
		}
		if($(this).text() == "show more matches") {
			$(this).text("show less matches");
			if($('#matchesContainer div.match_images.visible').size() > 5) {
				$('#matchesContainer').css('height', '100%');
				$('#matchesContainer').css('margin-top', '0px');
			}
		}
		else {
			$(this).text("show more matches");
			$('#matchesContainer').css('height', '50%');
			$('#matchesContainer').css('margin-top', '120px');
		}
	});
	
	$('.btnCloseWindow').click(function(event){
		maximize(false);
		showContainer($('#'+previousWindow), "dynamic");
		if((previousWindow == 'container-show-matches') || (previousWindow == 'container-matches')) {
			$('.right_column_wrap1').css('display', 'none');
		}
		else {
			$('.right_column_wrap1').css('display', 'block');
		}
	});
	
	$('.footer_links').click(function(event){
		event.preventDefault();
		var page = $(this).attr('page');
//		console.log("page="+page);
		var activeWindow = getActiveWindow();
		if(activeWindow == "") {
			activeWindow = "container-main";
			showContainer($('#container-main'), "dynamic");
			$('.validate').hide();
		}
		if($('#'+activeWindow).hasClass('static-pages')) {
		}
		else {
			if(activeWindow == 'container-celeb-info') {
				
			}
			else {
				previousWindow = activeWindow;
			}
			maximize(true);
		}
		showContainer($('#container-'+page+'-left'), "dynamic-left");
		showContainer($('#container-'+page+'-right'), "dynamic-right");
		showContainer($('#container-'+page), "dynamic");
	});
	
	$('#btnFacebook').click(function() {
		showContainer($('#container-facebook'), "dynamic");
		if($('#user_uid').attr('value') != undefined) {
			$('#btnTakePhoto').show();
		}
		else {
			$('#btnTakePhoto').hide();
		}
	});
	
	$('#btnCloseAlbum').click(function(){
		$('#facebook-photos').hide();
		$('#facebook-albums').show();
	});
	
	$('#btnFacebookUploadClose').click(function(){
		$('#facebook-photo').hide();
		$('#container-facebook-logged').show();
	});
	
	$('#btnFacebookUpload').click(function(){
		showContainer($('#container-main'), "dynamic");
		$('#form-upload-facebook').submit();
	});
	
	$('#btnCloseCollage').click(function(){
		showContainer($('#container-show-matches'), "dynamic");
	});
	
	$('#btnCollage').click(function(){
		var api = $("#scroll-matches").scrollable();
		var item = api.getItems().eq(api.getClickIndex());
		var matchId = item.attr('matchid');
		
		$('#txt-match-id').attr('value', matchId);
		$('#txt-uid').attr('value', $('#user_uid').attr('value'));
		$('#form-create-collage').submit();
	});
	
	$('#btnDownload').click(function(){
		var url = $('#img-collage').attr('src');
		url = "http://"+$("#txt-hostname").attr('value')+"/index/download/file/"+basename(url)+"/act/d";
		$("#a-download").attr("href", url);
		$('<form action="'+ url +'" method="post"></form>').appendTo('body').submit().remove();

//		$.post(url, function(data){
//			alert(data);
//		});
	});
	
	$('#btnShare').click(function(){
		var href = 'http://'+$('#txt-hostname').attr('value');
		var name = "Visit " + href + " to get your own celebriy matches!";;
		var imageLink = $(this).attr('link');
		var message = 'take a look at my celebrity matches!'; 
		var attachment = { 
		    'name': name, 
		    'href': href, 
		    'media': [{ 
		        'type': 'image', 
		        'src': imageLink, 
		        'href': imageLink}] 
		}; 
		var action_links = [{'text':'Recaption this', 'href': href}];

		FB.ui({
			method: 'stream.publish',
	     	message: message,
	     	attachment: attachment,
	     	action_links: action_links
	   	});
	});
}

function maximize(bool) {
var tmpWidth;

	if(bool) {
		tmpWidth = $('.center_column_wrap1').css('width');
		if(tmpWidth != '100%') {
			centerWidth = tmpWidth;
			$('.left_column_wrap1').css('display', 'none');
			$('.right_column_wrap1').css('display', 'none');
			$('.center_column_wrap1').css('width', '100%');
		}
	}
	else {
		if((previousWindow == "container-show-matches") || 
		   (previousWindow == "container-celeb-info") ) {
		}
		else {
			$('.right_column_wrap1').css('display', 'block');
		}
		$('.left_column_wrap1').css('display', 'block');
		$('.center_column_wrap1').css('width', centerWidth);
	}
}

function getActiveWindow() {
	var id = '';
	$('.dynamic').each(function() {
		if($(this).is(':visible')) {
			id = $(this).attr('id');
		}
	});
	return id;
}

function showMyMatches(myMatches) {
var tmpWindow;

	maximize(false);
	tmpWindow = getActiveWindow();
	if(tmpWindow != "container-show-matches") {
		currentWindow = tmpWindow;
	}
	showLogIn(false, $('#account_menu'), "fast");
	showContainer($('#container-show-matches'), "dynamic");
	showContainer($('#container-show-matches-left'), "dynamic-left");
	showContainer($('#container-show-matches-right'), "dynamic-right");
	drawMyMatches(myMatches);
	$('.right_column_wrap1').hide();
}

function saveResults() {
	var tmplIds='';
	$('#cmd_save-results').attr('value', 'save_results');
	$('#results-gender').attr('value', userGender);
	$('#results-user_picture').attr('value', selected);
	$('#uid').attr('value', $('#user_uid').attr('value'));
	$('#matchesContainer div.match_images.visible').each(function(){
		if(tmplIds != "") tmplIds=tmplIds+"|";
		tmplIds = tmplIds + $(this).attr('tmplId');
	});
	$('#results-tmplIds').attr('value', tmplIds);
	$('#form-save-results').submit();
}

function clearMatches() {
	return;
	var api = $("#scroll-matches").scrollable(); 
	if(api != undefined) {
		api.seekTo(0);
		$("#scroll-matches .items_matches").empty();
	 	api.reload().begin();
	 	$('.vNextPage').addClass('disabled');
	}
}

function showContainer(objContainer, objClass, display) {
var fnd = false;

	$('.'+objClass).each(function() {
		if($(this).is(':visible')) {
			//alert(objContainer.attr('id')+": visible");
			fnd = true;
			$(this).hide();
			$(objContainer).show();
			
			return;
			//$(this).fadeOut("fast", function() {
			//	$(objContainer).fadeIn("fast");
				//alert("hu");
				//return;
			//});
		}
	});
	
	if(!fnd) {
		$(objContainer).fadeIn("fast");
	}
}

function fillUpForm(clear) {
	var id = $('#user_uid').attr('value');
	var email = $('#user_email').attr('value');
	var passwd = $('#user_raw_password').attr('value');
	var nickname = $('#user_nickname').attr('value');
	var age = $('#user_age').attr('value');
	var birthdate = $('#user_birthdate').attr('value');
	var gender = $('#user_gender').attr('value');
	var country = $('#user_country').attr('value');
	
	if(clear) {
		id='';
		email='';
		passwd='';
		nickname='';
		age='';
		birthdate = '';
		country = '';
	}
	$('#txt_user_id').attr('value', id);
	$('#txt_nickname').attr('value', nickname);
	$('#txt_email').attr('value', email);
	$('#display_txt_email').attr('value', email);
	$('#txt_password').attr('value', passwd);
	$('#txt_confirm_password').attr('value', passwd);
	$('#txt_birthdate').attr('value', birthdate);
	if(gender == "Male") {
		$('#opt_male').attr('checked', 'checked');
	}
	else {
		$('#opt_female').attr('checked', 'checked');
	}
}

function startOver() {
	$('#subject_image').attr('src', '');
	$('#uploaded_image').attr('src', '/images/blank.png');
	$('#subject_image').attr('src', '');
	$('.getstarted').css('background-image', 'url(/images/default.jpg)');
	$('#data_file').attr('value', '');
	$('#canvas').empty();
	$('#canvas').append('<img id="subject_image"></img>');
	removeFaces();
	clearMatches();
	$('#match_image').attr('src', '');
	$('#user_image').attr('src', '');
	$('#uploaded_image').css('height', "auto");
	$('#uploaded_image').css('width', "auto");
	
	showContainer($('#container-main'), "dynamic");
	showContainer($('#container-main-left'), "dynamic-left");
	showContainer($('#container-main-right'), "dynamic-right");
	
	var loginVisible = false;
	if($('#user_uid').attr('value') != undefined) {
		loginVisible = true;
	}
	$('.login-only').each(function(){
		if(loginVisible) {
			$(this).show();
			$('#tip3').hide();
			$('#btnTakePhoto').show();
		}
		else {
			$('#tip3').show();
			$(this).hide();
			$('#btnTakePhoto').hide();
		}
	});
	
	userGender = '';
	$('.right_column_wrap1').show();
	$('#container-get-started').css('display', 'block');
}

function faceMatch() {
	userGender = '';
	$('input[name="gender_checkbox"]').each(function() {
		if($(this).attr('checked')) {
			if(userGender === '') {
				userGender = $(this).attr('value');
			}
			else {
				userGender = 'B';
			}
		}
	});
	if(userGender == '') userGender = 'B';
	var api = $("#scroll-detected").scrollable(); 
	selected = faces[api.getClickIndex()].image;
	$('#cmd_results').attr('value', 'face_match');
	$('#gender').attr('value', userGender);
	$('#user_picture').attr('value', selected);
	$('#form-results').submit();
}

function checkEntries(email, passwd, cpasswd, errorObj, strict) {
	var error='';
	if($.trim(email) != "") {
		if(isValidEmail(email)) {
			if(strict) {
		    	if($.trim(passwd) != "") {
			    	if($.trim(cpasswd) != "") {
			    		if(passwd == cpasswd) {
			    			return true;
			    		}
			    		else {
			    			error='Password not verified!';
//			    			showMessage("Password not verified!", $(errorObj));
			    		}
			    	}
			    	else {
			    		error='Please confirm password!';
//			    		showMessage("Please confirm password!", $(errorObj));
			    	}
		    	}
		    	else {
		    		error = 'Please input password!';
//		    		showMessage("Please input password!", $(errorObj));
		    	}
			}
			else {
				return true;
			}
		}
		else {
			error = 'Please input a valid e-mail address!';
//			showMessage("Please input a valid e-mail address!", $(errorObj));
		}
	}
	else {
		error = 'Please input your e-mail address!';
//		showMessage("Please input your e-mail address!", $(errorObj));
	}
	postIt(error, 'Error', 0);
	return false;
}

function isValidEmail(email) {
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email);
}

function showMessage(msg, obj) {
	$(obj).html(msg);
	$(obj).show();
}

function toggleScrollImage(show) {
	if(show) {
		$(".login_dropdown").attr('src', "/images/top_pullup.jpg");
	}
	else {
		$(".login_dropdown").attr('src', "/images/top_dropdown.jpg");
	}
}

function showLogIn(what, obj, duration, callback) {
	if(what) {
		$(obj).slideDown(duration, function() {
			toggleScrollImage(what);
			if(callback) callback();
		});
		$(obj).addClass('imopen');
	}
	else {
		$(obj).removeClass('imopen');
		$(obj).slideUp(duration, function(){
			toggleScrollImage(what);
			if(callback) callback();
		});
	}
}

function showMenu(code) {
	switch(code) {
		case 0:
			break;
	}
}

function initializeDialogs() {
	$('#dialog').dialog({
		autoOpen: false,
		modal: true,
		width: 500,
		height: 150,
		resizable: false,
		title: 'System Message',
		close: function(event, ui) {
			$(this).dialog('option', 'height', 150);
			$(this).dialog('option', 'title', 'System Message');
		},
		buttons: {
			"Ok": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	
	$('#dialog-confirm').dialog({
		autoOpen: false,
		modal: true,
		width: 500,
		height: 150,
		resizable: false,
		close: function(event, ui) {
			$(this).dialog('option', 'height', 150);
			$(this).dialog('option', 'title', 'System Message');
		},
		buttons: {
			"Ok": function() { 
				doTask();
				$(this).dialog("close"); 
			},
			"Cancel": function() { 
				$(this).dialog("close"); 
			}
		}
	});
	
	$('#dialog-prompt').dialog({
		autoOpen: false,
		modal: true,
		width: 500,
		height: 150,
		resizable: false,
		close: function(event, ui) {
			$(this).dialog('option', 'height', 150);
			$(this).dialog('option', 'title', 'System Message');
		},
		buttons: {
			"Ok": function() { 
				switch(task) {
					case "fdd":
						break;
				}
				$(this).dialog("close"); 
			},
			"Cancel": function() { 
				$(this).dialog("close"); 
			}
		}
	});
	
	$('#dialogUpload').dialog({
		autoOpen: false,
		width: 450,
		modal: true,
		buttons: {
			"Close": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	
	$('#dialogImage').dialog({
		autoOpen: false,
		width: '90%',
		height: '500',
		modal: true,
		buttons: {
			"Close": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
}

function initialize() {
	var loginOpt = $('#login_opt').attr('value');
	var userEmail = $('#user_email').attr('value');
	var userNickname = $('#user_nickname').attr('value');
	
	if(userNickname != '') {
		$('#display_nickname').html(userNickname+"!");
	}
	else {
		$('#display_nickname').html(userEmail+"!");
	}
	if(parseInt(loginOpt) > 0) {
		showLogIn(true, $('#signin_menu'), 0);
	}
	else {
		showLogIn(false, $('#signin_menu'), 0);
	}
	
	/*
	if($('#error-content').html() != null) {
		$('#error-content').show();
	}
	else {
		$('#error-content').hide();
	}
	*/
	$('#modal').jqm({modal: true, toTop: true});
	//getCountriesValues();
	
	$('.front_content_wrap').show();
	$('.front_content_wrap2').hide();
	
	
	/*showContainer($('#container-detect'));
	$('#subject_image').attr('src', "/uploads/1271843923012266200.jpg");
	$('.getstarted').css('background-image', 'url()');
	*/
	
	$("#scroll-detected").scrollable({
		vertical: true,
		size: 3, 
		clickable: true,
		nextPage: ".vNextPage",
		prevPage: ".vPrevPage"
	}).navigator().mousewheel();
	
	$("#scroll-matches").scrollable({
		vertical: true,
		size: 3, 
		clickable: true,
		nextPage: ".vNextPage2",
		prevPage: ".vPrevPage2"
	}).navigator().mousewheel();

	showContainer($('#container-main-left'), "dynamic-left");
	showContainer($('#container-main-right'), "dynamic-right");
	
	$('#uploaded_image').attr('src', '/images/blank.png');
	
	var errorMsg = $('#error-content').html();
	if(($.trim(errorMsg) != "") && (errorMsg != null)) {
		postIt(errorMsg, "Error", 0, true);
		if(parseInt(loginOpt) == 1501) {
			$('.gritter-without-image').append(
				"<br><p>Haven't received validation email?</p>"+
				"<p><a id=\"resend-validation\" class=\"footerlinks \" style=\"text-decoration: underline\" href=\"#\">Resend email validation</a></p>"
			);
			$('#resend-validation').click(function(event){
				event.preventDefault();
				$('.post-it').hide();
				$('#form-resend-validation').submit();
				return false;
			});
		}
	}
	
	doNot=false;
	
	centerToScreen();
	if($('#user_uid').attr('value') != undefined) {
		$('#btnTakePhoto').show();
		$('#btnSaveResults').show();
	}
	else {
		$('#btnTakePhoto').hide();
		$('#btnSaveResults').hide();
	}
	
	if($('#on-validate').attr('value') == "yes") {
		initAjax('#form-validate-account', prepareAjax, resultsAjax, '/api/?method=validateAccount&return=json');
		
		$('#form-validate-account').submit();
	}
	
	if($('#start-page').attr('value') != "") {
		switch($('#start-page').attr('value')) {
			case 'facebook':
				showContainer($('#container-facebook'), "dynamic");
				break;
		}
	}
	
	if($('#facebook-user-id').attr('value') != "") {
		loadFacebookProfile();
		loadFacebookAlbums();
	}
	else {
		$('#container-facebook-login').show();
		$('#container-facebook-logged').hide();
	}
//	showMain();
}

function loadFacebookProfile() {
	$('#container-facebook-login').hide();
	$('#container-facebook-logged').show();
	FB.api('/me', function(response) {
		$('#facebook-profile-name').html(response.name);
	});
}

function fqlGetAlbums(uid, callback){
	var queryStr = "SELECT aid, owner, cover_pid, name, size from album where owner={0}";
	var query = FB.Data.query(queryStr, uid);
	query.wait(function(rows) {
		callback(rows);
	});
}

function fqlGetPhotoById(id, callback, hash){
	var queryStr = "SELECT pid, aid, owner, src_small, src_small_height, src, caption from photo where pid={0}";
	var query = FB.Data.query(queryStr, id);
	query.wait(function(rows) {
		callback(rows, hash);
	});
}

function fqlGetPhotos(aid, callback){
	var queryStr = "SELECT pid, aid, owner, src_small, src_small_height, src_small_width, src_big, caption from photo where aid={0}";
	var query = FB.Data.query(queryStr, aid);
	query.wait(function(rows) {
		callback(rows);
	});
}

function showAlbums(albums) {
	var accessToken = $('#facebook-access-token').attr('value');	
	
	$('#container-facebook-albums').empty();
	for (var i=0; i < albums.length; i++) {
		var pid = albums[i].cover_pid;
		var hash = new Array(albums[i].aid, albums[i].name, albums[i].size);
		
		fqlGetPhotoById(pid, function(response, hash){
			var aid = hash[0];
			var aname = hash[1];
			var asize = hash[2];
			var src = response[0].src_small;
			var imgHeight = parseFloat(response[0].src_small_height)+10;
			
			$('#container-facebook-albums').append(
				'<div style="position: relative; width: 90%; margin-left: 50px; height: '+imgHeight+'px;">'+
					'<a href="#" class="album_links" aname="'+aname+'" aid="'+aid+'">'+
						'<img style="background-image: url(/images/loader.gif); float: left" src="'+src+'" />'+
						'<div style="float: left; padding: 10px;">'+
							'<span class="native_font" style="font-size: 14px;">'+
								aname+
								" ("+
								asize+
								")"+
							'</span>'+
						'</div>'+
					'</a>'+
				'</div>'
			);
			
			$('.album_links').click(function(){
				var aid = $(this).attr('aid');
				var aname = $(this).attr('aname');
				
				fqlGetPhotos(aid, function(photos) {
					$('#container-facebook-photos').empty();
					
					if(photos.length > 0) {
						for (var i=0; i < photos.length; i++) {
							$('#container-facebook-photos').append(
								'<div style="float: left; padding: 5px; width: 130px; height:100px; overflow: hidden">'+
									'<a href="#" class="album_photos" pid="'+photos[i].pid+'" pic="'+photos[i].src_big+'">'+
										'<img style="background-image: url(/images/loader.gif); background-repeat: no-repeat;" width="130px" src='+photos[i].src_small+' />'+
									'</a>'+
								'</div>'
							);
						}
						$('.album_photos').click(function(){
							var pic = $(this).attr('pic');
							$('#facebook-img').css('width', '220px');
							$('#facebook-img').css('height', '19px');
							$('#facebook-img').attr('src', '/images/loader.gif');
//							$('#facebook-img').css('background-image', 'url(/images/loader.gif)');
							$('#facebook-img').attr('src', pic);
							$('#facebook-photo').show();
							$('#container-facebook-logged').hide();
						});
					}
					$('#txtAlbumName').html(aname);
					$('#facebook-photos').show();
					$('#facebook-albums').hide();
				});
			});
		}, hash);
	}
}

function loadFacebookAlbums() {
	var accessToken = $('#facebook-access-token').attr('value');	
	var uid = $('#facebook-user-id').attr('value');
	var query;
	
	fqlGetAlbums(uid, function(rows){
		showAlbums(rows);
	});
	
//	FB.api('/me/albums?access_token='+accessToken, function(response) {
//		showAlbums(response.data);
//	});
	$('#facebook-photos').hide();
	$('#facebook-albums').show();
}

function centerToScreen() {
	var ph = window.innerHeight;
	if(ph == undefined) {
		if (document.documentElement && document.documentElement.clientWidth) {
      		ph = document.documentElement.clientHeight;
		}
		else if (document.body) {
			ph = document.body.clientHeight;
		}
	}
	var ah = $('.allwrap').height();
	var mh = (ph - ah) / 2;
//	console.log("ah="+ah+";ph="+ph+";mh="+mh);
	if(mh<0) {
		mh = 0;
	}
	$('.container').css('margin-top', mh);
	if ($.browser.msie && $.browser.version.substr(0,1)<8) {
		$('.topnav').css('margin-top', 10);
		$('.mContainer').css('margin-top', 10);
		$('div.items_detected').css('margin-left', -110);
	}
}

function initializeUploader() {
	var uploadButton = new AjaxUpload("btnUpload", {
			action: '/index/do/upload/file',
			name: "data-file",
			data: {
				"invoker": "upload_photo",
				"file-type": "img"
			},
			responseType: "json",
			autoSubmit: true,
			onSubmit: function(file, extension) {
				prepareUpload();
			},
			onComplete: function(file, response) {
				var title;
				var msgType = 0;
				
				var status = response.success;
				var cmd = response.cmd;
				
				hideBusy();
				if(status) {
					$('#uploaded_image').attr('src', response.file);
					$('#btnDetect').trigger('click');
				}
				else {
					$('.getstarted').css('background-image', 'url(/images/default.jpg)');
			    	title = "Error";
			    	msgType = 0;
			    	postIt(response.message, title, msgType);
			    }
			}
   	});
   	if($('#btnGetStarted').attr('id')) {
   		var uploadButton2 = new AjaxUpload('btnGetStarted', {
			action: '/index/do/upload/file',
			name: "data-file",
			data: {
				"invoker": "upload_photo",
				"file-type": "img"
			},
			responseType: "json",
			autoSubmit: true,
			onSubmit: function(file, extension) {
				prepareUpload();
			},
			onComplete: function(file, response) {
				var title;
				var msgType = 0;
				
				var status = response.success;
				var cmd = response.cmd;
				
				hideBusy();
				if(status) {
					$('#uploaded_image').attr('src', response.file);
					$('#btnDetect').trigger('click');
				}
				else {
					$('.getstarted').css('background-image', 'url(/images/default.jpg)');
			    	title = "Error";
			    	msgType = 0;
			    	postIt(response.message, title, msgType);
			    }
			}
   		});
   	}
}

function showMain() {
	selected = 'http://api.starsinyou.com/downloads/1280201388068282800_0.jpg';
	$('#user_image').attr('src', selected);
	
	var viewSize = drawFaceMatches(matches, $('#matchesContainer'), true);
	if(viewSize == 0) {
		$('#btnShowMatchesResults').text("show more matches");
	}
	else {
		$('#btnShowMatchesResults').text("show less matches");
	}
//	$('#matchesContainer2').hide();
//	$('#matchesContainer').show();
//	$('#btnShowMatchesResults').text("show more matches");
//	$('#matchesContainer').css('height', '50%');
//	$('#matchesContainer').css('margin-top', '120px');
	showContainer($('#container-matches'), "dynamic");
	showContainer($('#container-matches-left'), "dynamic-left");
	showContainer($('#container-matches-right'), "dynamic-right");
	$('.right_column_wrap1').hide();
	userGender = 'B';
	
	/*
	$('#subject_image').attr('src', '/uploads/1279683439034901900.jpg');	
	$('#subject_image').css('margin-top', 32.5);
	$('#subject_image').css('width', 580);
	$('#subject_image').css('height', "auto");
	
	drawDetectedFaces(faces);
	$('input[name="gender_checkbox"]').attr('checked', 'checked');
	showContainer($('#container-detect'), "dynamic");
	showContainer($('#container-detect-left'), "dynamic-left");
	showContainer($('#container-detect-right'), "dynamic-right");
	*/
}

function doTask() {
	switch(task) {
		case "process_file":
			break;
	}
}

function initAjax(obj, callBackBefore, callBackResponse, url) {
	var options = { 
        beforeSubmit:  	callBackBefore,  // pre-submit callback 
        success:       	callBackResponse,  // post-submit callback 
        url:			url,         // override for form's 'action' attribute 
        type:      		'post',        // 'get' or 'post', override for form's 'method' attribute 
        dataType:  		'json'        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
 
        // $.ajax options can be used here too, for example: 
        //timeout:   3000 
    }; 
 	
    // bind form using 'ajaxForm' 
    
    $(obj).ajaxForm(options);
}

function prepareAjax(formData, jqForm, options) { 
	hasTask = true;
	showBusy();
}

function prepareUpload(formData, jqForm, options) {
	showContainer($('#container-main'), "dynamic");
	$('#uploaded_image').attr('src', '/images/blank.png');
	$('.getstarted').css('background-image', 'url(/images/blank.png)');
	$('#container-get-started').css('display', 'none');
	if($('#user_uid').attr('value') != undefined) {
		$('#btnTakePhoto').show();
	}
	$('.validate').hide();
	showBusy();
}

function drawDetectedFaces(faces) {
	var api = $("#scroll-detected").scrollable(); 
 	
	for(face in faces) {
		// append new item using jQuery's append() method 
	    api.getItemWrap().append(
	    	'<div class="detected_images" idx="'+face+'" style="margin: 5px; text-align: center">'+
	    		'<img src="'+faces[face].image+'"/>' +
			'</div>'
	    );
	    
	    var x = faces[face].x;
	    var y = faces[face].y;
	    var w = faces[face].w;
	    var h = faces[face].h;
	    
	    //alert("x="+x+";y="+y+";w="+faces[face].w+";h="+faces[face].h+";ww="+w+";hh="+h);
	    
//	    $('#canvas').drawRect(x, y, w, h, {color: 'red', stroke: 2});
		
	}
	api.reload().end();
	api.begin();
	api.click(0);
	if(api.getPageAmount()>1) {
		$('.nextPage').removeClass('disabled');
	}
}

function doAnimation(image) {
	$('#user_image').fadeOut("", function(){
		$('#match_image').fadeOut("", function(){
			$('#match_image').attr('src', image);
			$('#user_image').fadeIn();
			$('#match_image').fadeIn("", function(){
				$('#user_image').animate({
					left: '+=50'
				}, 1000, function() {
				    // Animation complete.
				});
				$('#match_image').animate({
					left: '-=50'
				}, 1000, function() {
				    // Animation complete.
				});
			});
		});
	});
}

function drawMyMatches(myMatches) {
	var api = $("#scroll-matches").scrollable(); 
	api.getItemWrap().empty();
	
	for(match in myMatches) {
		// append new item using jQuery's append() method 
		var arr = match.split('|');
		var image = arr[0];
		var gender = arr[1];
		var timeStamp = arr[2];
		var id = arr[3];
		switch(gender) {
			case 'B':
				gender = 'Both';
				break;
			case 'M':
				gender = 'Male';
				break;
			case 'F':
				gender = 'Female';
				break;
		}
		api.getItemWrap().append( 
	    	'<div class="my_match_images" idx="'+match+'" matchid="'+id+'" style="float: left; text-align: center; position: relative;">'+
	    		'<div style="float: left; width: 75px; margin-left: 2px;">'+
	    			'<img src="'+image+'" height="80px" width="69px" style="float: left" />'+
	    		'</div>'+
	    		'<div style="float: right; width: 80px;">'+
		    		'<table border="0" width="100%" height="100%" style="border: 0px; padding: 0px; margin-top: -5px;">'+
		    			'<tr>'+
		    				'<td>'+
		    					'<div class="ui-state-default ui-corner-all xButton2" style="width: 18px; height: 18px; position: relative; float: right; margin-right: -23px; left: -23px;">'+
					    			'<span class="ui-icon ui-icon-closethick"></span>'+
					    		'</div>'+
		    				'</td>'+
		    			'</tr>'+
		    			'<tr>'+
		    				'<td>'+
		    					'<span class="native_font">'+timeStamp+'</span><br>'+
			    				'<span class="native_font">Gender: '+gender+'</span>'+
		    				'</td>'+
		    			'</tr>'+
		    		'</table>'+
		    	'</div>'+
	    		'<!--div class="ui-state-default ui-corner-all xButton2" style="width: 18px; height: 18px; position: relative; float: right; margin-right: -23px; left: -23px;">'+
	    			'<span class="ui-icon ui-icon-closethick"></span>'+
	    		'</div>'+
	    		'<img src="'+image+'" height="80px" width="69px" style="float: left" />'+
	    		'<div style="float: right">'+
		    		'<span class="native_font">'+timeStamp+'</span><br>'+
		    		'<span class="native_font">Gender: '+gender+'</span>'+
	    		'</div-->'+
			'</div>'
	    );
	}
	var firstIdx = '';
	
	$('.my_match_images').each(function(){
		var idx = $(this).attr('idx');
		var  matchId = $(this).attr('matchid');
		if(firstIdx == '') firstIdx = idx;
		$(this).click(function(event){
			var viewSize = drawFaceMatches(myMatches[idx], $('#myMatchesContainer'), false);
			if(viewSize == 0) {
				$('#btnShowMatches').text("show more matches");
			}
			else {
				$('#btnShowMatches').text("show less matches");
			}
		});
	});
	
	$('.xButton2').click(function(event){
    	event.preventDefault();
    	var id = $(this).parent().parent().parent().parent().parent().parent().attr('matchId');
    	//var id = $(this).parent().parent().parent().parent().parent().parent().attr('class');
    	
    	$('#match-id').attr('value', id);
    	$('#form-delete-result').submit();
    	return false;
	});
	
	api.reload();
	api.begin();
	api.click(0);
	if(api.getPageAmount()>1) {
		$('.vNextPage2').removeClass('disabled');
	}
	var viewSize = drawFaceMatches(myMatches[firstIdx], $('#myMatchesContainer'), false);
	if(viewSize == 0) {
		$('#btnShowMatches').text("show more matches");
	}
	else {
		$('#btnShowMatches').text("show less matches");
	}
}

function drawFaceMatches(tMatches, matchContainer, closeable) {
	var image;
	var name;
	var score;
	var id;
	var tmplId;
	
	matchContainer.empty();
	for(match in tMatches) {
		// append new item using jQuery's append() method 
		id = tMatches[match].id;
		tmplId = tMatches[match].tmplId;
		image = tMatches[match].image;
		name = tMatches[match].name;
		score = tMatches[match].score;
//		score = parseFloat((tMatches[match].score/180)*100);
		
//		if(score < 50) {
//			score+=40;
//		}
//		score = score.toFixed(2)+"%";
		
		matchContainer.append( 
	    	'<div class="match_images visible" style="cursor: pointer; float: left; text-align: center; height: 205px;" celebInfoId="'+id+'" tmplId="'+tmplId+'">'+
	    		'<div class="ui-state-default ui-corner-all xButton" style="width: 18px; left: 120px; position: relative; float: left; margin-right: -23px;">'+
	    			'<span class="ui-icon ui-icon-closethick"></span>'+
	    		'</div>'+
	    		'<img src="'+image+'" width="140px" height="160px"">'+
	    		'<div style="height: 5px;"></div>'+
	    		'<div style="overflow: hidden; width: 135px;">'+
	    			'<span class="native_font ellipsis" style="color: #000000;">'+name+'</span>'+
	    		'</div>'+
		        '<span class="native_font" style="color: #000000">'+score+'</span>'+
		        '<!--span class="native_font tooltip" style="background-color: #d883d8; padding: 4px; margin-top:-13px;" >'+name+'</span-->'+
			'</div>'
	    );
	}
	
	$('.match_images').click(function(event){
		if(hasTask) return;
		var celebInfoId = $(this).attr('celebInfoId');
		selectedCeleb = $(this).find("img").attr('src');
		$('#celeb-info-id').attr('value', celebInfoId);
		$('#cmd_celeb-info').attr('value', 'get_celeb_info');
		$('#form-celeb-info').submit();
	});
	$('.match_images').mousemove(function(event) {
		$(this).css('background-color', '#d883d8');
    });
    $('.match_images').mouseout(function(event) {
		$(this).css('background-color', '');
    });
    $('.ui-state-default').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);
    $('.xButton').click(function(event){
    	event.preventDefault();
    	var myId = matchContainer.attr('id');
    	var cnt = $('#'+myId+' div.match_images.visible').size();
    	
    	if(cnt > 1) {
    		$(this).parent().css('display', 'none');
    		$(this).parent().removeClass('visible');
	    	if(cnt == 6) {
				if(matchContainer.css('height') == '100%') {
					matchContainer.css('height', '50%');
					matchContainer.css('margin-top', '120px');
				}
			}
    	}
    	else {
    		postIt('Oops! The matches result must not be empty!', "Warning", 0);
    	}
    	
    	return false;
	});
	$('.xButton').css('display', 'none');
	if(closeable) {
		if($('#user_uid').attr('value') == undefined) {
		}
		else {
			$('.xButton').css('display', 'block');
		}
	}
	var myId = matchContainer.attr('id');
	var cnt = $('#'+myId+' div.match_images').size();
	if(cnt <= 5) {
		if(matchContainer.css('height') == '100%') {
			matchContainer.css('height', '50%');
			matchContainer.css('margin-top', '120px');
			matchContainer.addClass('forced');
			return 1;
		}
	}
	else {
		if(matchContainer.hasClass('forced')) {
			matchContainer.removeClass('forced');
			matchContainer.css('height', '100%');
			matchContainer.css('margin-top', '0px');
		}
	}
	return (matchContainer.css('height') == '100%')?1:0;
}

function removeFaces() {
	var api = $("#scroll-detected").scrollable(); 
	
	api.seekTo(0);
	$("#scroll-detected .items_detected").empty();
 	api.reload().begin();
 	$('.nextPage').addClass('disabled');
}

function resultsAjax(XMLHttp, postData)  { 
	var responseText = XMLHttp.responseText;
	var title;
	var msgType = 0;
	
	hasTask = false;
	if(!responseText) {
		var response = XMLHttp;
		if(typeof response == "string") {
			var response = $.evalJSON(response);
		}
	}
	else {
		var response = $.evalJSON(responseText);
	}
	
	var status = response.success;
	var cmd = response.cmd;
	hideBusy();
	switch(cmd) {
		case "register_user":
			if(status) {
//				var passwd = $('#txt_password').attr('value');
//		    	var tEmail = $('#txt_email').attr('value');
//		    	
//				$('#login_email').attr('value', tEmail);
//				$('#login_password').attr('value', passwd);
//				$('#form-signin').submit();
				postIt(response.message, "Register", 0);
				showLogIn(false, $('#register_menu'), 10);
				fillUpForm(true);
			}
			else {
//				showMessage(response.message, $('#register-error-content'));
				postIt(response.message, "Error", 0);
			}
			return true;
		case "edit_user":
			if(status) {
				var email = $('#txt_email').attr('value');
				var passwd = $('#txt_password').attr('value');
				var nickname = $('#txt_nickname').attr('value');
				var birthdate = $('#txt_birthdate').attr('value');
				var gender = $('#select_gender').attr('value');
				
				if($.trim(nickname) != "") {
					$('#display_nickname').html(nickname+"!");
				}
				else {
					$('#display_nickname').html(email+"!");
				}
				$('#user_raw_password').attr('value', passwd);
				$('#user_nickname').attr('value', nickname);
				$('#user_birthdate').attr('value', birthdate);
				$('#user_gender').attr('value', gender);
				
//				showMessage("Account updated!", $('#edit-register-error-content'));
				showLogIn(false, $('#edit_account_menu'), 600);
				postIt("Account updated!", "Edit Account", 0);
			}
			else {
//				showMessage(response.message, $('#edit-register-error-content'));
				postIt(response.message, "Edit Account", 0);
			}
			return true;
	}
	if(status) {
    	switch(cmd) {
    		case "get_images_web":
    			break;
    		case "upload_photo":
    			showContainer($('#container-main'), "dynamic");
    			$('.getstarted').css('background-image', 'url(/images/blank.png)');
    			$('#uploaded_image').attr('src', response.file);
				$('#btnDetect').trigger('click');
				return true;
			case "detect_faces":
				showContainer($('#container-detect'), "dynamic");
				showContainer($('#container-detect-left'), "dynamic-left");
				showContainer($('#container-detect-right'), "dynamic-right");
				drawDetectedFaces(response.faces);
				faces = response.faces;
				$('#subject_image').attr('src', response.link);
				$('input[name="gender_checkbox"]').attr('checked', 'checked');
				return true;
			case "start_over":
				startOver();
				return true;
			case 'face_match':
				matches = response.matches;
				$('#user_image').attr('src', selected);
				drawFaceMatches(matches, $('#matchesContainer'), true);
				$('#btnShowMatchesResults').text("show more matches");
				$('#matchesContainer').css('height', '50%');
				$('#matchesContainer').css('margin-top', '120px');
				showContainer($('#container-matches'), "dynamic");
				showContainer($('#container-matches-left'), "dynamic-left");
				showContainer($('#container-matches-right'), "dynamic-right");
				$('.right_column_wrap1').hide();
				if($('#user_uid').attr('value') != undefined) {
					$('#btnSaveResults').show();
				}
				else {
					$('#btnSaveResults').hide();
				}
				return true;
			case 'save_results':
				$('#btnSaveResults').hide();
				postIt('Results saved!', 'Save Results', 0);
				return true;
			case 'get_my_results':
				myMatches = response.matches;
				showMyMatches(myMatches);
				return true;
			case 'get_celeb_info':
				$('#imgSelectedCeleb').attr('src', selectedCeleb);
				$('#infoCategory').html(response.info['category_name']);
				$('#infoName').html(response.info['name']);
				$('#infoBirthdate').html(response.info['bday']);
				if(response.info['gender'] == 'M') {
					$('#infoGender').html("Male");
				}
				else {
					$('#infoGender').html("Female");
				}
				$('#infoCountry').html(response.info['country']);
				$('#infoDescription').html(response.info['description']);
				previousWindow = getActiveWindow();
				showContainer($('#container-celeb-info'), "dynamic");
				return true;
			case 'forgot_password':
				postIt('We have sent your password to your email address! Please check your email.', 'Forgot Password', 0);
				return true;
			case 'delete_result':
				var matchId = response.matchId;
				$('.my_match_images').each(function(){
					if($(this).attr('matchid') == matchId) {
						$(this).remove();
						
						var api = $("#scroll-matches").scrollable(); 
						api.reload();
						api.begin();
						if($('.my_match_images').size()>0) {
							api.click(0);
							$('.my_match_images:first').trigger('click');
						}
						else {
							$('#myMatchesContainer').empty();
						}
						postIt('Match result deleted!', 'Result Delete', 0);
						return true;
					}
				});
				return true;
			case 'validate_account':
				postIt("Email Verified. Your account has been activated!", "Account Validation", 0, true);
				return true;
			case 'resend_validation':
				$('.post-it').hide();
				postIt('Account validation sent! Please check your email.', "Account Validation", 0);
				return true;
			case 'create_collage':
				var link = "http://"+$('#txt-hostname').attr('value')+"/index/download/file/"+basename(response.image);
				$('#img-collage').attr('src', response.image);
				$('#btnShare').attr('link', response.image);
//				$('#a-fb-share').attr('href', "http://www.facebook.com/sharer.php?u="+link+"&t=Stars In You&m=message");
//				$('#rel-share').attr('href', link);
				
				showContainer($('#container-collage'), "dynamic");
				return true;
    	}
    }
    else {
    	switch(cmd) {
    		case "upload_photo":
//    			$('.getstarted').css('background-image', 'url(/images/default.jpg)');
    			break;
    		case "detect_faces":
//    			showContainer($('#container-main'), "dynamic");
//    			$('.getstarted').css('background-image', 'url(/images/default.jpg)');
//    			$('#uploaded_image').attr('src', '/images/blank.png');
//    			
//    			showContainer($('#container-take-photo'), "dynamic");
    			break;
    		case "validate_account":
    			postIt(response.message, "Account Validation", 0, true);
    			return true;
    		case 'resend_validation':
    			postIt(response.message, "Account Validation", 0);
    			return true;
    	}
    	title = "Error";
    	msgType = 0;
    }
    showDialog(response.message, title, msgType);
    return true;
}

function basename(file) {
	var parts = file.split('\\');
	if( parts.length < 2 )
	parts = file.split('/');
	return parts[ parts.length -1 ];
}

function postIt(msg, title, msgType, sticky) {
	$.gritter.add({
		// (string | mandatory) the heading of the notification
		title: '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+title,
		// (string | mandatory) the text inside the notification
		text: msg,
		// (string | optional) the image to display on the left
		image: "",
		// (bool | optional) if you want it to fade out on its own or just sit there
		sticky: sticky, 
		// (int | optional) the time you want it to be alive for before fading out (milliseconds)
		time: 5000,
		// (string | optional) the class name you want to apply directly to the notification for custom styling
		class_name: 'post-it',
	        // (function | optional) function called before it opens
		before_open: function(){
		},
		// (function | optional) function called after it opens
		after_open: function(e){
		},
		// (function | optional) function called before it closes
		before_close: function(e){
		},
		// (function | optional) function called after it closes
		after_close: function(){
		}
	});
}

function showDialog(msg, title, dialogType) {
var dialogB;

	switch(dialogType) {
		case 0:
			postIt(msg, title, 0, false);
			return;
			dialogB = $('#dialog');
			break;
		case -1:
			dialogB = $('#dialog');
			break;
		case 1:
			dialogB = $('#dialog-confirm');
			break;
		case 2:
			dialogB = $('#dialog-prompt');
			break;
	}
	if(title != "") {
		$(dialogB).dialog('option', 'title', title);
	}
	if(dialogType < 2) {	
		if(msg)	$(dialogB).html(msg);
	}
	else {
		$('#prompt-caption').html(msg);
		switch(promptType) {
			case 0: 		//textbox
				$('#prompt-select').hide();
				$('#prompt-text').show();
				break;
			case 1:			//selectbox
				$('#prompt-text').hide();
				$('#prompt-select').show();
				break;
		}
	}
	$(dialogB).dialog('open');
}

function showBusy(obj) {
	if(obj) {
		$('#uploaded_image').css('background-image', 'url(/images/loader.gif)');
	}
	else {
		$('#modal').jqmShow();
	}
}

function hideBusy() {
	$('#modal').jqmHide();
}

function initializeForms() {
	initAjax('#form-data-file', prepareAjax, resultsAjax, '/index/do/upload');
	initAjax('#form-upload', prepareUpload, resultsAjax, '/index/do/upload');
	initAjax('#form-detect', prepareAjax, resultsAjax, '/index/do/detect');
	initAjax('#form-register', prepareAjax, resultsAjax, '/api/?method=registerUser&return=json');
	initAjax('#form-account', prepareAjax, resultsAjax, '/api/?method=updateUser&return=json&oper=edit');
	initAjax('#form-forgot', prepareAjax, resultsAjax, '/api/?method=forgotPassword&return=json');
	initAjax('#form-start-over', prepareAjax, resultsAjax, '/api/?method=processResults&return=json');
	initAjax('#form-results', prepareAjax, resultsAjax, '/index/do/match');
	initAjax('#form-save-results', prepareAjax, resultsAjax, '/api/?method=saveResults&return=json');
	initAjax('#form-my-results', prepareAjax, resultsAjax, '/api/?method=getMyResults&return=json');
	initAjax('#form-celeb-info', prepareAjax, resultsAjax, '/api/?method=getCelebInfo&return=json');
	initAjax('#form-delete-result', prepareAjax, resultsAjax, '/api/?method=deleteResult&return=json');
	initAjax('#form-resend-validation', prepareAjax, resultsAjax, '/api/?method=resendValidation&return=json');
	initAjax('#form-upload-facebook', prepareAjax, resultsAjax, '/api/?method=uploadFacebook&return=json');
	initAjax('#form-create-collage', prepareAjax, resultsAjax, '/api/?method=createCollage&return=json');
}

function uploadDataFile(fileType, title, invoker) {
	var success=false;
	var message="error";
	hideBusy();
	$('#dialogUpload').dialog('option', 'title', title);
	$('#file-type').attr('value', fileType);
	$('#invoker').attr('value', invoker);
	$('#dialogUpload').dialog('open');
	
	return [success,message]; 
}

function getCountriesValues() {
	$.getJSON("/api/?method=getCountries", {"return":"values"}, function(data) {
		if (data != null) {
			countriesValues = data;
	    }
    });
}

$(document).ready(function () {
	initializeDialogs();
	initializeEvents();
	initializeForms();
	initializeUploader();
	initialize();
});

