// JavaScript Document

var existEmail="";
var existUname="";
var captcha=0;
var urlreg = "http://www.rockto.com/register/facebook";

function cekFB(){
	FB.Connect.requireSession(function() { 
		FB.Facebook.apiClient.users_hasAppPermission("publish_stream",function(msg) {
			if(msg==0){
				FB.Connect.showPermissionDialog("publish_stream,email",function(perms) {	
				});	
			}
		});							   
		window.location=urlreg; 
	});	
}

function form(regisUrl,status){
	url = regisUrl;
	if(status=="cekjs" || status=="register"){
		if(status=="register")
			$("#slider").css({"top": "-35px"});
			
		$("#joinBtn").livequery("click", function(event){
			$("#logoutBox").remove();
			$("#slider").animate({"top": "-=800px"}, "slow");
			return false;
		});	
		
		$.ajax({
			type: "POST",
			url: url,
			data: { key : "cek", ref : ref },
			success: function(msg){
				$(".cekjs").replaceWith(msg);
				Recaptcha.create("6LfZoAoAAAAAABPFM1omebvLQFiZ3EeDR5CY52H0", "captcha", {
						theme: "white",
						tabindex: 6
				});
				if($("#reg_email").val()=='')
					$("#reg_email").defaultvalue("dfemail","Email");
				$("#reg_fullname").defaultvalue("dffname","Fullname");
				if($("#reg_uname").val()=='')
					$("#reg_uname").defaultvalue("dfuname","Username");
				if($("#reg_pass").val()=='')
					$("#reg_pass").defaultvalue("dfpass","Password");
				if($("#reg_conf").val()=='')
					$("#reg_conf").defaultvalue("dfconf","Re-enter Password");
					
				$("#reg_pass, #reg_conf").livequery("focus", function(event){
					//if($("#reg_pass").val()!='')
					this.type = 'password';
				});
				$("#reg_pass, #reg_conf").livequery("blur", function(event){
					if($(this).val()=='Password' || $(this).val()=='Re-enter Password')
						this.type = 'text';
				});
				$(".reg_info").hide();
				$("#formRegis").ajaxForm({ 
					global : false,
					beforeSubmit: validate,
					beforeSend : function(){
						$("#formRegis button").html("registering...");
						$("#formRegis button").attr("disabled","disabled");
					},
					success: function(data) {
						window.location = data;
					}
				});
			}
		});
	}else{
		$("#loginBox").hide();
		$("#reg_email").defaultvalue("dfemail","Email");
		if($("#reg_uname").val()=='')
			$("#reg_uname").defaultvalue("dfuname","Username");
		$("#reg_pass").defaultvalue("dfpass","Password");
		$("#reg_exist_uname").defaultvalue("exuname","Username");
		$("#reg_exist_password").defaultvalue("expass","Password");
		$("#reg_pass, #reg_exist_password").livequery("focus", function(event){
			//if($("#reg_pass").val()!='')
			this.type = 'password';
		});
		$("#reg_pass, #reg_exist_password").livequery("blur", function(event){
			if($(this).val()=='Password')
				this.type = 'text';
		});
		$(".reg_info").hide();
		$("#btnAlready, .check-rockers").livequery("click", function(event){
			$(".error_box").hide();
			if(status=="facebook") 
				$("#slider2").animate({"top": "-=570px"}, "slow");
			else
				$("#slider2").animate({"top": "-=590px"}, "slow");
			$("#registExist").fadeIn("fast");
			return false;
		});
		$("#btnRegist").livequery("click", function(event){
			$(".error_box").hide();
			$("#slider2").animate({"top": "0px"}, "slow");
			$("#registExist").fadeOut("fast");
			return false;
		});
		$("#formRegis").ajaxForm({ 
			global : false,
			beforeSubmit: validate2,
			beforeSend : function(){
				$("#formRegis button").html("registering...");
				$("#formRegis button").attr("disabled","disabled");
			},
			success: function(data) {
				window.location = data;
			}
		});
		$("#formExist").ajaxForm({ 
			global : false,
			beforeSubmit: validate3,
			beforeSend : function(){
				$("#formExist button").html("connecting...");
				$("#formExist button").attr("disabled","disabled");
			},
			success: function(data) {
				var sp = data.split("##");
				if(sp[0]=="error"){
					alert(sp[1]);
					$("#formExist button").html("Connect");
					$("#formExist button").removeAttr("disabled");
					$("#reg_email").defaultvalue("dfemail","Email");
					$("#reg_exist_uname").defaultvalue("exuname","Username");
					$("#reg_exist_password").defaultvalue("expass","Password");
					$("#reg_exist_password").livequery("focus", function(event){
						//if($("#reg_pass").val()!='')
						this.type = 'password';
					});
					$("#reg_exist_password").livequery("blur", function(event){
						if($(this).val()=='Password')
							this.type = 'text';
					});
				}else{
					window.location = data;
				}
			}
		});
	}
	
	$("input[name*=reg]").livequery("focus", function(event){
		var id = "#"+$(this).attr("id")+"_error";
		$(id).hide();
		//$(this).next().next(".reg_info").fadeIn("slow");
	});
	
	//check rockers
	checkRockers();
	
	$("input[name*=reg]").livequery("blur", function(event){
		$(".reg_info").hide();								
	});
	
	$("#reg_email").livequery("blur", function(event){
		var email = $(this).val();
		cekEmailExist(email,url);
	});
	
	$("#reg_email").livequery("change", function(event){
		existEmail = "";
		var email = $(this).val();
		cekEmailExist(email,url);
	});
		
	$("#reg_uname").livequery("blur", function(event){
		var uname = $(this).val();
		cekUnameExist(uname,url);
	});
	
	$("#reg_uname").livequery("change", function(event){
		existUname = "";
		var uname = $(this).val();
		cekUnameExist(uname,url);
	});
	
	//$("#formRegis").livequery("submit", function(event){
//		if(status=="cekjs" || status=="register")
//			return validate(url);
//		else
//			return validate2(status,url);
//	});


	
	$("#formLogin").livequery("submit", function(event){
		return validate3();
	});
	
	slctTopic();
	chgImg();
	saveThumb();
}
function cek(formData, jqForm, options){
	var usernameValue = $("#reg_uname").fieldValue();
    var passwordValue = $("#reg_pass").fieldValue();
    // usernameValue and passwordValue are arrays but we can do simple
    // "not" tests to see if the arrays are empty
    if (!usernameValue[0] || !passwordValue[0]) {
        alert('Please enter a value for both Username and Password');
        return false;
    }
    alert('Both fields contain values.');
}

function slctTopic(){
	$(".chooseTopic").livequery("click", function(event){
		if(!$(this).hasClass("disabled")){
			var friend = $(this).html();
			var topicid = $(this).attr("topicid");
			var cur = $(this);
			var cek = true;
			if(!$(this).hasClass("selected")){
				$("#selectedTopics input").each(function(index) {
					var isi = $(this).val();
					if(isi==topicid){
						cek = false;
						alert("topic selected already");
					}
				});
				if(cek){
					$(cur).addClass("selected");
					hid = $("<input>").attr({
						name: "topic[]",
						value: topicid,
						type: "hidden"
					}).appendTo("#selectedTopics");
				}
			}else{
				$(this).removeClass("selected");
				$("#selectedTopics").find("input[value=\'"+topicid+"\']").remove();
			}
		}else{
			alert("You've already followed this topic");		
		}
		return false;
	});
	
	$("a.submitSuccess").livequery("click", function(event){
		var cek = $("#selectedTopics input").length;
		if(cek>=5)
			$("#submitSuccess").submit();
		else
			alert("Please choose 5 topics minimum.");
		return false;
	});
	
	$("a.submitFinnish").livequery("click", function(event){
		$("#submitFinnish").submit();
		return false;
	});
	
	$("div.btnFollow").livequery("click", function(event){
		var targetID = $(this).attr("targetID");
		if(targetID){
			var classs = "."+targetID;
			var cur = $(this);
			var order = $(this).attr("order");
			var list = $("#list").val();
			$.ajax({
				global : false,
				beforeSend : function(){
					$(cur).removeAttr("targetID");
					$(classs).fadeTo("fast", 0.5);
				},  
				type: "POST",
				url: urlUser+"/follow",
				data: { targetID : targetID, status : "follow", order : order, from : "suggestion", list : list },
				timeout: 60000,
				success: function(msg){
					var spl = msg.split("##");
					if(spl[0]=="success"){
						$(classs).fadeTo("fast", 0);
						if(spl[1]!=undefined){
							$(classs).replaceWith(spl[1]);
							if(spl[2]!=undefined)
								$("#list").val(spl[2]);
						}else
							$(classs).remove();
					}else{
						$(classs).fadeTo("fast", 1);
						$(cur).attr("targetID",targetID);
						$.jGrowl(spl[1]);
					}
				}
			});
		}
		return false;
	});
	
	$("#userfile").livequery("change", function(event){
		$(".frm_upload").submit();
	});
}

function chgImg(){
	$(".error").hide();
	$(".frm_upload").ajaxForm({
		global : false,
		beforeSend : function(){
			$("#img-thumb").fadeTo("fast", 0.5);
			$("#formTool").hide();
		},
		success: function(data) {
			var spl = data.split("#");
			if (spl[0]=="error"){
				$(".error").html(spl[1]);
				$(".error").show();
				$("#formTool").show();
			}else{
				$('#imgsubheader').html("One last step. Pick your thumbnail and we're all set");
				$("#img-thumb").html('<img src="'+spl[1]+'_original'+spl[2]+'" style="float: left; margin-right: 10px;" id="thumbnail" alt="Create Thumbnail" width="50%"/><div style="border:1px #e5e5e5 solid; float:left; position:relative; overflow:hidden; width:200px; height:200px;"><img src="'+spl[1]+'_original'+spl[2]+'" style="position: relative;" id="thumbnail_preview" alt="Thumbnail Preview" /></div><input type="hidden" name="x1" value="" id="x1" /><input type="hidden" name="y1" value="" id="y1" /><input type="hidden" name="x2" value="" id="x2" /><input type="hidden" name="y2" value="" id="y2" /><input type="hidden" name="w" value="" id="w" /><input type="hidden" name="h" value="" id="h" /><hr class="space"/><input type="submit" name="save_thumb" value="Save Thumbnail" id="save_thumb" />');	
				$("#img-thumb").fadeTo("fast", 1);
				$('#img-thumb').find('#thumbnail').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview, minWidth: 200, minHeight: 200, handles: true });	
				
			}
		}
	});
}

function preview(img, selection) { 
	//get width and height of the uploaded image.
	var current_width = $('#img-thumb').find('#thumbnail').width();
	var current_height = $('#img-thumb').find('#thumbnail').height();
	
	var scaleX = 200 / selection.width; 
	var scaleY = 200 / selection.height; 
	
	$('#img-thumb').find('#thumbnail_preview').css({ 
		width: Math.round(scaleX * current_width) + 'px', 
		height: Math.round(scaleY * current_height) + 'px',
		marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
		marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
	});
	$('#x1').val(selection.x1);
	$('#y1').val(selection.y1);
	$('#x2').val(selection.x2);
	$('#y2').val(selection.y2);
	$('#w').val(selection.width);
	$('#h').val(selection.height);
} 

function saveThumb(){
	$('#save_thumb').livequery("click", function(event){
		var x1 = $('#x1').val();
		var y1 = $('#y1').val();
		var x2 = $('#x2').val();
		var y2 = $('#y2').val();
		var w = $('#img-thumb').find('#thumbnail_preview').width();
		var h = $('#img-thumb').find('#thumbnail_preview').height();
		var curw = $('#img-thumb').find('#thumbnail').width();
		var curh = $('#img-thumb').find('#thumbnail').height();
		if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
			alert("You must make a selection first");
			return false;
		}else{
			//hide the selection and disable the imgareaselect plugin
			$('#img-thumb').find('#thumbnail').imgAreaSelect({ disable: true, hide: true }); 
			$.ajax({
				global : false,
				beforeSend : function(){
					$("#save_thumb").attr("value","saving..");
					$("#save_thumb").attr("class","btn-submit-disabled text span-3");
					$("#save_thumb").attr("disabled","disabled");
				},
				type: 'POST',
				url: urlUser+'/save-img-prof',
				data: { x1 : x1, y1 : y1, x2 : x2, y2 : y2, w : w, h : h, curw : curw, curh : curh, from : "register" },
				cache: false,
				success: function(response){
					var spl = response.split("##");
					if(spl[0]=='success'){
						$('#imgsubheader').html("That's it! It's a wrap! Let's start rockin'");
						$("#img-thumb").html(spl[1]);
					}
				}
			});
			
			return false;
		}
	});	
}

function cekEmailExist(email,url){
	if(email!="Email"){
		$.ajax({
			type: "POST",
			url: url,
			data: { email : email, key : "email" },
			success: function(msg){
				existEmail = msg;
			}
		});	
	}
}

function cekUnameExist(uname,url){
	$.ajax({
		type: "POST",
		url: url,
		data: { uname : uname, key : "uname" },
		success: function(msg){
			existUname = msg;
		}
	});
}

function checkRockers(){
	$(".check-rockers").livequery("click", function(event){
		var id = $(this).attr("id");
		var status = $(this).attr("status");
		if(status=="rock"){
			$(".form-reg").hide();
			$(".form-login-exist").show("slow");
			$(".check-rockers").attr("status","not");
			$(".check-rockers").html("I'm not a rockers yet! I want to register");
		}else{
			$(".form-login-exist").hide();
			$(".form-reg").show("slow");
			$(".check-rockers").attr("status","rock");
			$(".check-rockers").html("Already a Rockers? click here.");
		}
		return false;
	});	
}

function validate(formData, jqForm, options){
	var status = new Array(1,1,1,1,1);
	var setfoc = new Array(0,0);
	var isiCaptcha  = $("#captcha").html();
	if(isiCaptcha=="")
		captcha=0;
	$(".error_box").hide();
	cekEmail(status,setfoc,url);
	cekUname(status,setfoc,url);
	cekPass(status,setfoc);
	cekConf(status,setfoc);
	cekFullname(status,setfoc,url);
	//cekIsiCaptcha(status);
	if(status=="0,0,0,0,0"){
		if(captcha!=1){
			//return true;
//		}else{
			return cekCaptcha(url);
		}
	}else{
		captcha = 0;
		Recaptcha.reload();	
		return false;
	}
}

function validate2(formData, jqForm, options){
	var cek = new Array(1,1,1);
	var setfoc = new Array(0,0);
	$(".error_box").hide();
	cekUname2(cek,setfoc,status,url);
	cekEmail2(cek,setfoc,status,url);
	cekPass(cek,setfoc);
	if(cek!="0,0,0"){
		//return true;
//	}else{
		return false;
	}
}

function validate3(formData, jqForm, options){
	var status = new Array(0,1,1);
	var setfoc = new Array(0,0);
	$(".error_box").hide();
	cekUname3(status,setfoc);
	cekPass2(status,setfoc);
	if(status!="0,0,0"){
		//return true;
//	}else{
		return false;
	}
}

function cekCaptcha(url){
	//var captcha = $("#validate").val();
	var response = String($("#formRegis").find("#recaptcha_response_field").fieldValue());
	var challenge = String($("#formRegis").find("#recaptcha_challenge_field").fieldValue());
	var hasil = "";
	$.ajax({  
		global : false,
		beforeSend : function(){
			$("#reg_captcha_error").html("Please Wait. Validating Captcha.");
			$("#reg_captcha_error").show();
		},
		type: "POST",
		url: url,
		data: { challenge : challenge, response : response, key : "captcha" },
		success: function(msg){
			$("#reg_captcha_error").hide();
			captcha = msg;
			if(msg==1){
				$("#formRegis").submit();
			}else{
				$("#reg_captcha_error").html("Please enter the valid captcha.");
				$("#reg_captcha_error").show();
				Recaptcha.reload();
				return false;
			}
		}
	});	
	return false;
}

function cekEmail(status,setfoc,url){
	var email = String($("#reg_email").fieldValue());
	if(email=="" || email=="Email"){
		$("#reg_email_error").html("Please enter your email address.");
		$("#reg_email_error").show();
		status[0] = 1;
	}else{
		
		cekEmailExist(email,url);
		
		if(!isValidEmail(email)){
			$("#reg_email_error").html("Please enter valid email address.");
			$("#reg_email_error").show();
			status[0] = 1;	
		}else if(existEmail!=0){
			$("#reg_email_error").html("Your email is already exist in our database.");
			$("#reg_email_error").show();
			status[0] = 1;	
		}else{
			status[0] = 0;	
		}
	}
}

function cekEmail2(cek,setfoc,status,url){
	var fbmail = String($("#fb_email").fieldValue());
	if(fbmail=="" || fbmail==undefined){
		var email = String($("#reg_email").fieldValue());
		if(email==""){
			$("#reg_email_error").html("Please enter your email address.");
			$("#reg_email_error").show();
			cek[0] = 1;
		}else{
			cekEmailExist(email,url);
			if(!isValidEmail(email)){
				$("#reg_email_error").html("Please enter valid email address.");
				$("#reg_email_error").show();
				cek[0] = 1;	
			}else if(existEmail!=0){
				$("#reg_email_error").html("Your email is already exist in our database. <a href=\"\" class=\"check-rockers\" id=\""+status+"\" status=\"rock\">Already a Rockers? click here to login.</a>");
				$("#reg_email_error").show();
				cek[0] = 1;	
			}else{
				cek[0] = 0;	
			}
		}
	}else{
		cek[0] = 0;	
	}
}

function cekUname(status,setfoc,url){
	var uname = String($("#reg_uname").fieldValue());
	if(uname=="" || uname=="Username"){
		$("#reg_uname_error").html("Please enter your username.");
		$("#reg_uname_error").show();
		status[1] = 1;
	}else{
		
		cekUnameExist(uname,url);
		if(uname.length > 16){
			$("#reg_uname_error").html("Sorry, your username is too long. max. 16 char(s)");
			$("#reg_uname_error").show();
			status[1] = 1;	
		}else if(existUname!=0){
			$("#reg_uname_error").html("Sorry, your username is already taken. ");
			$("#reg_uname_error").show();
			status[1] = 1;	
		}else if(uname.match(/\W/)){
			$("#reg_uname_error").html("Sorry, no special character allowed for username.");
			$("#reg_uname_error").show();
			status[1] = 1;			  
	 	}else{
			status[1] = 0;	
		}
	}
}

function cekFullname(status,setfoc,url){
	var fname = $("#reg_fullname").fieldValue();
	if(fname=="" || fname=="Fullname"){
		$("#reg_fullname_error").html("Please enter your fullname.");
		$("#reg_fullname_error").show();
		status[4] = 1;
	}else{
		status[4] = 0;	
	}
}

function cekUname2(cek,setfoc,status,url){
	var uname = String($("#reg_uname").fieldValue());
	if(uname=="" || uname=="Username"){
		$("#reg_uname_error").html("Please enter your username.");
		$("#reg_uname_error").show();
		cek[1] = 1;
	}else{
		cekUnameExist(uname,url);
		if(uname.length > 16){
			$("#reg_uname_error").html("Sorry, your username is too long.");
			$("#reg_uname_error").show();
			cek[1] = 1;	
		}else if(existUname!=0){
			$("#reg_uname_error").html("Sorry, your username is already taken. <a href=\"\" class=\"check-rockers\" id=\""+status+"\" status=\"rock\">Already a Rockers? click here to login.</a>");
			$("#reg_uname_error").show();
			cek[1] = 1;	
		}else if(uname.match(/\W/)){
			$("#reg_uname_error").html("Sorry, no special character allowed for username.");
			$("#reg_uname_error").show();
			cek[1] = 1;				  
	 	}else{
			cek[1] = 0;	
		}
	}
}

function cekUname3(status,setfoc){
	var uname = String($("#reg_exist_uname").fieldValue());
	if(uname=="" || uname=="Username"){
		$("#reg_email_user_error").html("Please enter your registered email or username.");
		$("#reg_email_user_error").show();
		status[1] = 1;
	}else{
		status[1] = 0;	
	}
}

function cekPass(status,setfoc){
	var pass = String($("#reg_pass").fieldValue());
	if(pass=="" || pass=="Password"){
		$("#reg_pass_error").html("Please enter your password.");
		$("#reg_pass_error").show();
		status[2] = 1;
	}else{
		if(pass.length < 6){
			$("#reg_pass_error").html("Please enter a password that is at least 6 characters long.");
			$("#reg_pass_error").show();
			status[2] = 1;
		}else{
			status[2] = 0;	
		}
	}
}

function cekPass2(status,setfoc){
	var pass = String($("#reg_exist_password").fieldValue());
	if(pass=="" || pass=="Password"){
		$("#reg_password_error").html("Please enter your password.");
		$("#reg_password_error").show();
		status[2] = 1;
	}else{
		status[2] = 0;	
	}
}

function cekConf(status,setfoc){
	var pass = String($("#reg_pass").fieldValue());
	var conf = String($("#reg_conf").fieldValue());
	if(conf=="" || conf=="Password"){
		$("#reg_conf_error").html("Please enter the confirmation password.");
		$("#reg_conf_error").show();
		status[3] = 1;
	}else{
		if(conf != pass){
			$("#reg_conf_error").html("Make sure the password you enter are the same.");
			$("#reg_conf_error").show();
			status[3] = 1;
		}else{
			status[3] = 0;	
		}
	}
}

function isValidEmail(str){
	var s = $.trim(str);
	var at = "@";
	var dot = ".";
	var lat = s.indexOf(at);
	var lstr = s.length;
	var ldot = s.indexOf(dot);

	if (s.indexOf(at)==-1 ||
	   (s.indexOf(at)==-1 || s.indexOf(at)==0 || s.indexOf(at)==lstr) ||
	   (s.indexOf(dot)==-1 || s.indexOf(dot)==0 || s.indexOf(dot)==lstr) ||
	   (s.indexOf(at,(lat+1))!=-1) ||
	   (s.substring(lat-1,lat)==dot || s.substring(lat+1,lat+2)==dot) ||
	   (s.indexOf(dot,(lat+2))==-1) ||
	   (s.indexOf(" ")!=-1))
	{
	  return false;
	}

	return true;
}

function approved(email){
	$("#fb_email").attr("value",email);
	$("#fb_perm").hide();
	$("#reg_email_error").hide();
	$("#reg_email").attr("value","Facebook Email");
	$("#reg_email").attr("disabled","disabled");
}

