//var todbpath = 'http://v2.nickindia.com/db/';
var todbpath = 'http://www.nickindia.com/db/';

var SITEPATH = "http://www.nickindia.com/";

var signInreload;
var isdocReady = 0; //variable for too stop popup to be open until page is load
$(function(){isdocReady = 1;});

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function setcookieinter( name, value, expires, path ){
	var today = new Date();
		today.setTime( today.getTime() );
	if ( expires )
		{
		expires = expires * 1000 * 60 * 60 ;//* 24;
		}
		
		var expires_date = new Date( today.getTime() + (expires) );
		
		document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" );
		
}
function setcookie( name, value ){
	var expires_date = "int()''";
	document.cookie = name + "=" +escape( value );
}
//-----------------------------------------------------------register

function register(){
	_gaq.push(['_trackPageview', '/registation.html']);
	$.blockUI(divREG, {width:'413px', top: '35%'});
	//captchaRefresh("regGlu");
	/*if ( FB.XFBML.Host.parseDomTree ){
		 setTimeout( FB.XFBML.Host.parseDomTree, 0 );
	}*/
}

function closeregister()
{
	$.unblockUI();
}

function validateSignup(){
	var fname = $.trim($("#fname").val());
	var lname = $.trim($("#lname").val());
	//var bday = $.trim($("#bday").val());
	//var bmonth = $.trim($("#bmonth").val());
	//var byear = $.trim($("#byear").val());
	var uesrname = $.trim($("#username").val());
	var password = $.trim($("#password").val());
	var confirmPas = $.trim($("#confirmPassword").val());
	var alernateEmail = $.trim($("#alernateEmail").val());
	var confirmCode = $.trim($("#confirm_code").val());
	var terms = $("#regTerms").is(":checked");
	$("#regErrormsg").html("");
	if(fname == ""){
		//alert("Please Enter First Name.");
		$("#regErrormsg").html("Please Enter First Name.");
		$("#fname").focus();
		return false;
	}
	if(lname == ""){
		//alert("Please Enter Last Name.");
		$("#regErrormsg").html("Please Enter Last Name.");
		$("#lname").focus();
		return false;
	}
	
	/*if(bday == "" || bmonth == "" || byear == ""){
		alert("Please Select Your Birth Date.");
		return false;
	}*/
	
	if(uesrname == ""){
		//alert("Please Enter Username.");
		$("#regErrormsg").html("Please Enter Username.");
		$("#uesrname").focus();
		return false;
	}
	
	if (isalphanumeric(uesrname) == false) {
		$("#regErrormsg").html("Username contains invalid characters.");
		$("#uesrname").focus();
		return false;
	}
	
	if(password == ""){
		//alert("Please Enter Password.");
		$("#regErrormsg").html("Please Enter Password.");
		$("#password").focus();
		return false;
	}else if(password.length < 6){
		//alert("Password should be 6 characters or more.");
		$("#regErrormsg").html("Password should be 6 characters or more.");
		$("#password").focus();
		return false;
	}
	
	if(confirmPas == ""){
		//alert("Please Enter Confirm Password.");
		$("#regErrormsg").html("Please Enter Confirm Password.");
		$("#confirmPassword").focus();
		return false;
	}
	
	if(password != confirmPas){
		//alert("Password and Confirm Password Does not match");
		$("#regErrormsg").html("Password and Confirm Password Does not match");
		$("#confirmPassword").focus();
		return false;
	}
	
	if(alernateEmail == ""){
		//alert("Please Enter Alternate Email.");
		$("#regErrormsg").html("Please Enter Email.");
		$("#alernateEmail").focus();
		return false;
	}else{
		if(isValidEmail(alernateEmail) == false){
			//alert("Invalid Email Address");
			$("#regErrormsg").html("Invalid Email Address.");
			$("#alernateEmail").focus();
			return false;
		}
	}
	/*if(confirmCode == ""){
		//alert("Please Enter the text you see in the image.");
		$("#regErrormsg").html("Please Enter the text you see in the image.");
		$("#confirm_code").focus();
		return false;
	}*/
	
	if(terms == false){
		//alert("Please Click on accept the term of use.");
		$("#regErrormsg").html("Please Click on accept the term of use.");
		return false;
	}
	if($("#userflag").val()=="no")
	{
		$("#regErrormsg").html("Selected User name Not Available,select different username.");
		return false;
	
	}
	
	if($("#emailflag").val()=="no")
	{
		$("#regErrormsg").html("Selected email address already exists.");
		return false;
	
	}
	//$("#regForm").submit();
	var formData = $("#regForm").serialize();
	//alert(formData);
	$.ajax({
			   type: "POST",
			   url: SITEPATH+"register2db.php",
			   data: formData,
			   success: registerChk
			});
return true;
}

function registerChk(data){
	
	data_arr = data.split("|");
	if(data_arr[0] == "1"){
		var url=SITEPATH + "loginverify.php";
		$.getJSON(url+"?f_id="+data_arr[2]+"&f_pwd="+data_arr[3]+"", 
		function(data3){ 
			if(data3["status"] == "success"){
				setcookieinter("myid",data3["userid"],3,"/");
				setcookieinter("ses",data3["sessionid"],3,"/");
				
				$.post(SITEPATH+"check_map.php", {"uId":data3["userid"], "userName":data_arr[2], "Newuser":"yes"}, function(data2) {
					
						var data_arr = data2.split("|");
						
						document.getElementById('signin_info').innerHTML = "<p>Welcome <strong>"+data3["username"]+"</strong>  | <a href=\""+SITEPATH+"logout.php\" class=\"w_11L\">Logout</a></p>"; 
						if(data_arr[1] == "noFb"){ //means user  is not looged in using facebook
						//alert('hi');
						<!--document.getElementById('signin_info').innerHTML += " | <fb:login-button v=\"2\" size=\"small\" autologoutlink=\"false\" >Connect with Facebook</fb:login-button>";-->
						}
						FB.XFBML.parse();
						//$.unblockUI();
						closesignin();
				});
			}else{
				//$.unblockUI();	
				closesignin();
			}
		});
	}else{
		$("#regErrormsg").html(data);
	}
}

function isalphanumeric(str)
{
	 var bReturn = true;
	 var valid="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._-";
	 var invalidfirst = "._-";
	 var invalidlast = "._-";
	 for (var i=0; i<str.length; i++) {
	 if ( i == 0 && (invalidfirst.indexOf(str.charAt(i)) > 0)){
	 bReturn = false;
	 break;
	 }
	 else if ( i == (str.length-1) && (invalidlast.indexOf(str.charAt(i)) > 0)) {
	 bReturn = false;
	 break;
	 }
	 else if (valid.indexOf(str.charAt(i)) < 0) {
	 bReturn = false;
	 break;
	 }
	 }
	 return(bReturn);
} 

function Trim(str) {	
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function isValidEmail(str) 
{	
	if(str.length > 3)
	{
		emailRe = /^\w+([\.+-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|jobs|mobi|asia|tel|travel))$/
		if (!emailRe.test(str))	
		{
			return false;	
		}
		else
		{
			return true;				
		}
	}
	else
	{
		return false;	
	}
}
function isValidmobile(str) 
{
	mobileRe = /^([9]{1})([234789]{1})([0-9]{8})$/
	if (!mobileRe.test(str))	
		return false	
	else
		return true		
}

function clearInput(val){
	if(val == "First Name"){
		$("#fname").val('');
	}else
	if(val == "Last Name"){
		$("#lname").val('');
	}
}

function checkUsername(username){
	//alert(username);
	if($.trim(username) != ""){
		/*check for username available or not*/
		$("#usernameMsg").html("<img src='/images/L.gif'/>");
		$.post(SITEPATH+"checkusername.php", {'username': username, 'flag':'checkUsername'}, function(data) {
						//alert(data);
						if(data == "No"){ //
							$("#usernameMsg").html("");
							$("#usernameMsg").html("Selected User name Not Available.");
							$("#userflag").val("no");
						}else if(data == "Yes"){ $("#userflag").val("yes");
							$("#usernameMsg").html("Selected User name  Available.");
							$("#regErrormsg").html("Selected User name  Available.");
						}
				});
	}else{
		/*username suggestion*/
		$("#usernameMsg").html("");
	}
		var fname = $.trim($("#fname").val());
		var lname = $.trim($("#lname").val());
		if(fname != "" && lname != "" && fname != "First Name" && lname != "Last Name"){
			$.post(SITEPATH+"checkusername.php", {'fname': fname, 'lname':lname, 'flag':'usernameSuggestion'}, function(data) {
					$("#usernameSuggestion").html(data);
					
			});
		}else{
			$("#regErrormsg").html("Enter your name so we can suggest a new available Username");
		}
}

function checkEmialId(alernateEmail){
	//alert(username);
	if($.trim(alernateEmail) != ""){
		
		$.post(SITEPATH+"checkdupemail.php", {'email': alernateEmail, 'flag':'checkemail'}, function(data) {
						//alert(data);
						if(data == "No"){ //
							$("#emailMsg").html("");
							$("#emailMsg").html("Selected email already exist.");
							$("#emailflag").val("no");
						}else if(data == "Yes"){ $("#emailflag").val("yes");
							
						}
				});
	}else{
		/*username suggestion*/
		$("#emailMsg").html("");
	}
		
}

var var2 = $('#divsignin');
var divSI, divREG, divFP;
//divSI also defined in the footer
function checklogin(){
	_gaq.push(['_trackPageview', '/login.html']);
			$.blockUI(divSI, {width:'400px'});
			
			//$.blockUI(divREG, {width:'413px', top: '35%'});
	/*if(isdocReady){
		if(!readCookie("ui")){
			
		}
	}*/
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function closesignin()
{
	Close_Popup();
	
	//Changes on 15th July 2010 For Microsite Login END
	//window.location.reload();
}

//----------------comment-----------------------


function commentCountUpdate(contentId, tblName, idCloumn, contentType, contentTypeid, contentTitle, pgUrl){
	var formData = "id="+contentId+"&tblName="+tblName+"&idColumn="+idCloumn+"&contentType="+contentType+"&contentTypeid="+contentTypeid+"&contentTitle="+contentTitle+"&pgUrl="+pgUrl;

	$.ajax({
			   type: "POST",
			   url: todbpath+"comentCount2db.php",
			   data: formData,
			   success: function(data){ //alert(data);
				  var data_arr = data.split('|');
				  if(data_arr[0] == 1){
					  if(tblName == "vjtravelogue"){
					  	$('#con_comment_'+data_arr[1]).html(data_arr[2]);  
					  }else{
						  //alert(data_arr[2]);
					  	$('#con_comment_'+data_arr[1]).html(data_arr[2]);  
					  }
				  }
			   }
			});
}



var UNAME = '';
function LoginVerifynew(str){	
	//alert('hi');
	var usernm = $("#f_id_new").val();
	var pswrd = $("#f_pwd_new").val();
	UNAME = usernm;

	if(usernm == ""){
		alert("Enter username.");
		return false;
	}

	if(pswrd == ""){
		alert("Enter Password");
		return false;
	}

	var url=SITEPATH +"loginverify.php";
	$.getJSON(url+"?f_id="+usernm+"&f_pwd="+pswrd+"", 
	function(data){
		//alert(data["status"]);
		if(data["status"] == "success"){
			setcookieinter("myid",data["userid"],3,"/");
				setcookieinter("ses",data["sessionid"],3,"/");
				$.post(SITEPATH+"check_map.php", {"uId":data["userid"], "userName":UNAME}, function(data2) {//alert(data2);
					if(signInreload=='' || signInreload==null){
						//window.location.reload();
						var data_arr = data2.split("|");
							if(document.getElementById('signin_info')){
								document.getElementById('signin_info').innerHTML = "<p>Welcome <strong>"+data["username"]+"</strong>  | <a href=\""+SITEPATH+"logout.php\" class=\"w_11L\">Logout</a></p>"; 
								if(data_arr[1] == "noFb"){
								/*document.getElementById('signin_info').innerHTML += " | <fb:login-button v=\"2\" size=\"small\" autologoutlink=\"false\" >Connect with Facebook</fb:login-button>";*/
							}
						}
						FB.XFBML.parse();
						closesignin();
					}else if(signInreload==1){
						closesignin();
					}
				});
		}else{
			if(data["errorcode"] == '4'){
				$("#signinErrormsg").html("Userid does not exist.");
			}else{
				$("#signinErrormsg").html("The username or password you entered is incorrect.");
			}
		}
	});
}



//---------------------forgot passwprd


function forgetpassword(){
	$.blockUI(divFP, {width:'413px'});	
}

function closeFP(){
	$.unblockUI();
}

function forgotpwd()
{
	
	var url=todbpath + "forgot.php";
	
	var forgot_email = $("#forgot_email").val();
	if(forgot_email=="")
	{
		 $("#fpwdErrMsg").html("Please enter username.");
	}
	//var forgot_altemail = $("#forgot_altemail").val();
	$.getJSON(url+"?forgot_email="+forgot_email+"", 
	function(data){
		//alert(data);
		//console.debug(data);
		alert(data["status"]);
		if(data["status"] == "success"){
				closesignin();			
				alert('Forgot password link has been sent');				
		}else{
			 if(data['code']==1)
			  {
				   $("#fpwdErrMsg").html("This username is not available. Please try again.");
			  }
			  else
			  {
				$("#fpwdErrMsg").html("Failed to send the link. Please try again.");
			  }
		}
	});
}


     
function logincheck(){
	$("#signin_info").load(SITEPATH+"db/ajax_logincheck.php", function() {
			FB.XFBML.parse();

});

}
  function logincheck1(){
		var ajaxRequest1;  // The variable that makes Ajax possible!

		try{
			// Opera 8.0+, Firefox, Safari
			ajaxRequest1 = new XMLHttpRequest();
		} catch (e){
			// Internet Explorer Browsers
			try{
				ajaxRequest1 = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try{
					ajaxRequest1 = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e){
					// Something went wrong
					alert("Your browser broke!");
					return false;
				}
			}
		}
		// Create a function that will receive data sent from the server
		ajaxRequest1.onreadystatechange = function(){//alert(ajaxRequest1.readyState);
			if(ajaxRequest1.readyState == 4){
		//alert(ajaxRequest1.responseText);

				if(ajaxRequest1.responseText!="")
				{
					data=ajaxRequest1.responseText;
					data_arr = data.split("#");
					//alert($.trim(data_arr[0]));
					if($.trim(data_arr[0])=="oops" ){
						//alert('oops inside');
					document.getElementById("signin_info").innerHTML = data_arr[1];
					showNickReg();
					}
					else if($.trim(data_arr[0])=="yes" )
					{
							//alert('oops ourdside');
						document.getElementById("signin_info").innerHTML = data_arr[1];
						FB.XFBML.parse(document.getElementById('signin_info'));
					}
					
					
				}
			}
		}
		//alert(SITEPATH+"db/ajax_logincheck.php");
		ajaxRequest1.open("GET",SITEPATH+"db/ajax_logincheck.php", true);
		ajaxRequest1.send(null);

}


	
	
	function tvschedule()
			{
		var ajaxRequest1;  // The variable that makes Ajax possible!
		//alert('wait loading..');

		try{
			// Opera 8.0+, Firefox, Safari
			ajaxRequest1 = new XMLHttpRequest();
		} catch (e){
			// Internet Explorer Browsers
			try{
				ajaxRequest1 = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try{
					ajaxRequest1 = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e){
					// Something went wrong
					alert("Your browser broke!");
					return false;
				}
			}
		}
		// Create a function that will receive data sent from the server
		ajaxRequest1.onreadystatechange = function(){
			if(ajaxRequest1.readyState == 4){
				//alert(ajaxRequest1.responseText);

				if(ajaxRequest1.responseText!="")
				{
					document.getElementById("tvshedule").innerHTML = ajaxRequest1.responseText;
				
				}
			}
		}

		ajaxRequest1.open("GET",todbpath+"ajax_tvshow.php", true);
		ajaxRequest1.send(null);

			}

   
    

function facebook_onlogin_ready() {
  // In this app, we redirect the user back to index.php. The server will read
  // the cookie and see that the user is logged in, and will deliver a new page
  // with content appropriate for a logged-in user.
  //
  // However, a more complex app could use this function to do AJAX calls
  // and/or in-place replacement of page contents to avoid a full page refresh.

 
  refresh_page();
}

/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page() {
	//alert('oo');
	checkMapping1(); // IN general.js
	
}
function checkMapping(){
}
function checkMapping1(){
	//alert("done");
	$.post(SITEPATH+"db/check_mapping.php", {}, function(data) {
			//alert("map"+data);
			data_arr = data.split("#");
			if($.trim(data_arr[0])== "oops"){
				$('#signin_info').html(data_arr[1]);
								
				FB.XFBML.parse();
				
				//checklogin(); //YXP
				showNickReg();
			}else{
				
					$('#signin_info').html(data_arr[1]);
			
			}
	});
}
function Show_Popup(action, userid) {
$('#popup').fadeIn('fast');
$('#window').fadeIn('fast');
}
function Close_Popup() {
$('#popup').fadeOut('fast');
$('#window').fadeOut('fast');
}
function showNickReg(){
	Show_Popup();
/*$.get(SITEPATH+'db/registernick.php', function(data) {
											  // alert(data);
		$('#divRegMtv').html(data);
		
		//divRegMtv = $('#divRegMtv');
		//divRegMtv=document.getElementById('divRegMtv');
		
	   // $.blockUI(divRegMtv, {width:'400px', top:'40%'});
		//captchaRefresh("regGlumtv");
		//$('#regMtvFBmsg').html(fbSession.first_name);
	
		FB.XFBML.parse(document.getElementById('regMtvFBmsg'));
	});*/
}

function facebookLogout(facebook){
	
	if(facebook==1){
		 window.location.href=SITEPATH+'logout.php';
	
	}
	else
	{
		FB.logout(function(response) {
		 window.location.href=SITEPATH+'logout.php';
	}); 
	}
}


function nameToggle(){
		var fbname = $("#fbName").is(":checked");
		
		if(fbname == false){
			$("#nicknameTog").show();
		}else{
			$("#nicknameTog").hide();
		}
}

function clearName(name){
	if(name == "First Name"){
		$('#fnamenick').val('');
	}
	if(name == "Last Name"){
		$('#lnamenick').val('');
	}
}

var userNamemtv;
var userIdmtv;
function registerVerifyNick(){
	
	var validUser = $("#validUser").val();	
	var  alernateEmail = $("#alernateEmail").val();	
	var terms = $("#regTermsmtv").is(":checked");
	var fbName = $("#fbName").is(":checked");

	
	
	if(alernateEmail == ""){
		$("#regmtvErrorMsg").html("Please Enter Alternate Email Address.");
		return false;
	}
	
	if(isValidEmail(alernateEmail) == false){
		$("#regmtvErrorMsg").html("Invalid Email Address.");
		return false;
	}
	
	if(fbName == false){
		fnamenick = $("#fnamenick").val();
		lnamenick = $("#lnamenick").val();
		if(fnamenick == "" || fnamenick == "First Name"){
			$("#regmtvErrorMsg").html("Please Enter First Name.");
			return false;	
		}
		
		if(lnamenick == "" || lnamenick == "First Name"){
			$("#regmtvErrorMsg").html("Please Enter Last Name.");
			return false;	
		}
	
	}
	
	
	if(terms == false){
		$("#regmtvErrorMsg").html("Please Click on accept the term of use.");
		return false;
	}
	
	dataString = $("#regMtvUser").serialize();
	$.post(todbpath+"register2db.php", dataString, function(data) {
		//alert(data);
		$("#regmtvWait").html("<img src='/images/L.gif' alt='Please wait'/>");
		dataArr = data.split("#");
		//alert(data);
		/*userNamemtv = usernameMtv;
		userIdmtv = dataArr[4];*/
		if(dataArr[0] == "1"){
		//document.getElementById('signin_info').innerHTML = "Welcome <strong>"+dataArr[1]+"</strong>  | <a href=\""+SITEPATH+"logout.php\" class=\"w_11L\">Logout</a>"; 
									
									$("#signin_info").html(dataArr[1]);
									$("#regmtvWait").html("");
									closesignin();
						
						}else{
							$("#regmtvWait").html("");
							closesignin();
						}
					
					});
	
}

function captchaRefresh(id){
	var time = new Date().getTime();
	document.getElementById(id).src=SITEPATH+"captcha/CaptchaSecurityImages.php?ver="+time;
	return true;
}
