var $inde = jQuery.noConflict();
var BaseURL=getBaseURL();
var loadimg="<img src='"+BaseURL+"img/loading26.gif' alt='loading...'>";

//USED TO POPUP WINDOW
(function(jQuery){
    jQuery.oauthpopup = function(options)
    {
        options.windowName = options.windowName ||  'ConnectWithOAuth'; // should not include space for IE
        options.windowOptions = options.windowOptions || 'location=0,status=0,width=800,height=400';
        options.callback = options.callback || function(){ window.location.reload(); };
        var that = this;

        that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
        that._oauthInterval = window.setInterval(function(){
            if (that._oauthWindow.closed) {
                window.clearInterval(that._oauthInterval);
                options.callback();
            }
        }, 1000);
    };
})(jQuery);

$inde(document).ready(function(){
	//HIDE THE DEFAULT FLASH MESSAGE
   var flashMessage = $inde('#flashMessage');
   flashMessage.load();
	 setTimeout(function() {
		  $inde('#flashMessage').fadeOut('slow');
	  }, 2000);	

	$inde('.celeb_name').focus(function(){
		// check_username();
		// check_email();
		var this_val = $inde(this);
		// alert(this_val);
		$inde(".error_wrap").hide();
		$inde("#div_toc").hide();
		if(this_val.val() == ''){	
			$inde("#div_"+this_val.attr('id')).html('This is required field');
			$inde("#div_wrap_"+this_val.attr('id')).fadeIn('slow');
		}else{
			$inde("#div_"+this_val.attr('id')).html('');	
			$inde("#div_wrap_"+this_val.attr('id')).fadeOut('fast');		
		}
	});
	
	$inde("#ProfileChangePassword1").click(function(){
		$inde("#pass_sh_hid_div").show("fast");
		$inde("#hidde_val").val(1);
	});
	
	$inde("#ProfileChangePassword0").click(function(){
		$inde("#pass_sh_hid_div").hide("fast");
		$inde("#hidde_val").val(0);
	});
	
	
	$inde("#profileProfileForm").submit(function(){
		var username =  $inde("#username").val();
		var email =  $inde("#email").val();
		var hidde_val = $inde("#hidde_val").val();
		var password =  $inde("#password").val();
		var retype_pass =  $inde("#repassword").val();
		
		var data = $inde('#profileProfileForm').serialize();
		if(username == ''){	
			$inde("#div_username").html('Username id required');
			return false;
		}
		if(email == ''){	
			$inde("#div_email").html('Email id required');
			return false;
		}
		
		if(hidde_val == 1){
			if(password == ''){	
				$inde("#error_div_email").show();
				return false;
			}
			if(retype_pass == ''){	
				$inde("#div_pass1").show();
				return false;
			}
			
			if((password.length < 6) && (retype_pass.length < 6)){	
				$inde("#div_pass").show();
				return false;
			}
			if(password != retype_pass){	
				$inde("#div_pass2").show();
				return false;
			}	
		}
			var url = BaseURL+"change_profile"
			$inde.ajax({
				type: "POST",
				url: url,
				//dataType: 'json',
				data: data,
				success: function(resp){
					// alert(resp);
					//alert(resp.message);
					//alert(resp.active_id);
					if(resp == 'succ'){			
						window.location = BaseURL;
					}else if(resp == 'email'){			
						$inde("#div_email").html('Email already exists.');
						return false;
					}else if(resp == 'username'){
						$inde("#div_username").html('Username already taken try another!');
						return false;
					}else{
						alert('something went wrong');
						return false;
					}
				}
			});
		return false;
	});
	
	//Get the height of the first item
	var heigh = $inde('#mask').css({'height':$inde('#panel-1').height()});
	
	//Calculate the total width - sum of all sub-panels width
	//Width is generated according to the width of #mask * total of sub-panels
	$inde('#panel').width(parseInt($inde('#mask').width() * $inde('#panel div').length));
	
	//Set the sub-panel width according to the #mask width (width of #mask and sub-panel must be same)
	// alert($inde('#mask').width());
	$inde('#panel div').width($inde('#mask').width());
	
	//Get all the links with rel as panel
	$inde('a[rel=panel]').click(function () {
	
		//Get the height of the sub-panel
		var panelheight = $inde($inde(this).attr('href')).height();
		
		//Set class for the selected item
		$inde('a[rel=panel]').removeClass('selected');
		$inde(this).addClass('selected');
		
		//Resize the height
		$inde('#mask').animate({'height':panelheight},{queue:false, duration:500});			
		
		//Scroll to the correct panel, the panel id is grabbed from the href attribute of the anchor
		$inde('#mask').scrollTo($inde(this).attr('href'), 800);		
		
		//Discard the link default behavior
		return false;
	});
	
	$inde("#regist_btn").click(function(){
		var reg_btn_clicks = $inde("#reg_btn_clicks").val();
		if(reg_btn_clicks == 0){
			$inde("#log_in_div").hide();
			$inde("#signup_div").show();
			var image = 'url('+BaseURL+'img/login_unsel_btn.png)';
			var image2 = 'url('+BaseURL+'img/register_sel_btn.png)';
			$inde(this).css("background-image",image2);
			$inde("#signin_btn").css("background-image",image);
			$inde("#reg_btn_clicks").val(1);
			$inde("#login_btn_clicks").val(0);
		}else{
			
			//$inde('#signupIndexForm').submit(function(){
				check_username();
				check_email();
				$inde(".error_wrap").hide();
				$inde("#div_toc").hide();
				var data = $inde('#signupIndexForm').serialize();
				var prem_acct_val = $inde("#prem_acct_val").val();
				var prem_email_val = $inde("#prem_email_val").val();
				var email = $inde('#email').val();
				var password = $inde('#passwords').val();
				var retype_pass = $inde('#retype_pass').val();
				var first_name = $inde('#first_name').val();
				var last_name = $inde('#last_name').val();
				var user_name = $inde('#user_name').val();
				var toc = $inde('#toc').attr('checked');	
				// alert(password);
				// alert(retype_pass);
				// return false;
				
				if(user_name == ''){	
					$inde("#div_user_name").html('please give your name');
					$inde("#div_toc").show();
					$inde("#div_wrap_user_name").fadeIn('slow');
					return false;
				}
				
				if(prem_acct_val == 1){
					$inde("#div_user_name").html('username is already taken');
					$inde("#div_wrap_user_name").fadeIn('slow');
					return false;
				}
	
				if(!isValidEmailAddress(email)){	
					$inde("#div_email").html('please give valid email');
					$inde("#div_toc").show();
					$inde("#div_wrap_email").fadeIn('slow');
					return false;
				}
				
				if(prem_email_val == 1){
					$inde("#div_email").html('Email already taken . Try another!');
					$inde("#div_wrap_email").fadeIn('slow');
					return false;
				}
				
				if(password.length < 6){	
					$inde("#div_passwords").html('atleast 6 to 8 characters accepted');
					$inde("#div_toc").show();
					$inde("#div_wrap_passwords").fadeIn('slow');
					return false;
				}
				if(retype_pass.length < 6){
					$inde("#div_retype_pass").html('atleast 6 to 8 characters accepted');
					$inde("#div_toc").show();
					$inde("#div_wrap_retype_pass").fadeIn('slow');
					return false;
				}
				if(password != retype_pass){	
					$inde("#div_passwords").html('password does not match');
					$inde("#div_toc").show();
					$inde("#div_wrap_passwords").fadeIn('slow');
					return false;
				}
				
				// if(!toc){
					// $inde("#div_toc").html('please accept out terms and conditions');
					// $inde("#div_wrap_toc").fadeIn('slow');
					// return false;
				// } 
				$inde('#signupIndexForm').submit();
				
					return false;
			//});
		}		
	});
	
	$inde("#signin_btn").click(function(){
		var login_btn_clicks = $inde("#login_btn_clicks").val();
		if(login_btn_clicks == 0){
			$inde("#signup_div").hide();
			$inde("#log_in_div").show();
			var image = 'url('+BaseURL+'img/login_btn.png)';
			var image2 = 'url('+BaseURL+'img/register_btn.png)';
			//$inde(".note_fol_name").css("background-image",image);
			$inde(this).css("background-image",image);
			$inde("#regist_btn").css("background-image",image2);
			$inde("#login_btn_clicks").val(1);
			$inde("#reg_btn_clicks").val(0);
		}else{
			
			$inde("#div_toc").hide();
			var data = $inde('#loginIndexForm').serialize();
			var username = $inde('#username').val();
			var password = $inde('#password').val();
			// alert(username);
			if(username == ''){
				$inde("#error_wrong_image_user").show();
				$inde("#error_right_image_user").hide();
				return false;
			}else{
				$inde("#error_wrong_image_user").hide();
				$inde("#error_right_image_user").show();
			}
			
			if(password == ''){
				$inde("#error_wrong_image_pass").show();
				$inde("#error_right_image_pass").hide();
				return false;
			}else{
				$inde("#error_wrong_image_pass").hide();
				$inde("#error_right_image_pass").show();
			}
			
			var url = BaseURL+"user_login"
			// var all = 'all';
			$inde.ajax({
				type: "POST",
				url: url,
				dataType: 'json',
				// data: "search_text="+search_text+"&age="+age+"&locations="+locations,
				data: data,
				success: function(res){
					// alert(res);
					// alert(res.message);
					if(res.message == 'success'){
						window.location = BaseURL+'/';
					}else{
						$inde("#error_right_image_pass").hide();
						$inde("#error_right_image_user").hide();
						$inde("#error_wrong_image_user").show();
						$inde("#error_wrong_image_pass").show();
						return false;
					}
					
					
				}
			});	
		}		
	});
	
	/* drop down box*/
	 // $inde('.default').dropkick();
	 
	$inde("#commentsShowMovieForm").submit(function(){
		var logged_val = $inde("#logged_val").val();
		if(logged_val == 0){
			alert('Plase log in and then post your reviews.');
			window.location = BaseURL;
		}else{
			var data = $inde("#commentsShowMovieForm").serialize();
			// alert(data);
			var review_txt = $inde("#review_txt").val();
			var rating_output = $inde("#rating_output").val();
			if(review_txt == ''){
				alert("Post reviews and submit!");
				return false;
			}
			if(rating_output == 0){
				var accpt = confirm("Do you like Post review without rating this movie?");
				if(accpt){
					var url = BaseURL+"review_submit"
					$inde("#ajax_review_show").html(loadimg);
					$inde.ajax({
						type: "POST",
						url: url,
						//dataType: 'json',
						data: data,
						success: function(res){
							// alert(res);
							if(res == 'error'){
								alert('Review not posted. Try again!');
								return false;
							}else{
								$inde("#review_txt").val('');
								$inde("#rating_output").val(0);
								$inde("#ajax_review_show").html(res);
							}
						}
					});	
				}
				return false;	
			}else{
				var url = BaseURL+"review_submit"
				$inde("#ajax_review_show").html(loadimg);
				$inde.ajax({
					type: "POST",
					url: url,
					//dataType: 'json',
					data: data,
					success: function(res){
						// alert(res);
						if(res == 'error'){
							alert('Review not posted. Try again!');
							return false;
						}else{
							$inde("#review_txt").val('');
							$inde("#rating_output").val(0);
							$inde("#ajax_review_show").html(res);
						}
					}
				});	
			}
			return false;
		}	
	});
	
});

function check_username(){
	var user_name = $inde("#user_name").val();
	var url = BaseURL+"checkusername"
	$inde.ajax({
		type: "POST",
		url: url,
		//dataType: 'json',
		data: "user_name="+user_name,
		success: function(res){
			$inde("#prem_acct_val").val(res);
		}
	});	
}

function check_email(){
	var email = $inde("#email_l").val();
	var url = BaseURL+"checkemail"
	$inde.ajax({
		type: "POST",
		url: url,
		//dataType: 'json',
		data: "email="+email,
		success: function(res){
			$inde("#prem_email_val").val(res);
		}
	});	
}

function vote_increase(movie_id,title,desc){
	// alert(movie_id);
	var logged_val = $inde("#logged_val").val();
	if(logged_val == 0){
		alert('Plase log in and then Vote.');
		window.location = BaseURL;
	}else{
		// var accpt = confirm("Do you like to vote for this Movie?");
		// if(accpt){
			var url = BaseURL+"vote_movies"
			$inde.ajax({
				type: "POST",
				url: url,
				//dataType: 'json',
				data: "movie_id="+movie_id,
				success: function(res){
					if(res == 0){
						alert('Voted successfully');
						var story = '/movie/'+movie_id+'-'+title;
						publish(title,desc,null,story);
					}else{
						alert(res);
					}
				}
			});	
		// }
	}	
} 

function vote_decrease(movie_id){
	// alert(movie_id);
	var logged_val = $inde("#logged_val").val();
	if(logged_val == 0){
		alert('Plase log in and then Vote.');
		window.location = BaseURL;
	}else{
		var accpt = confirm("Do you like to un-vote for this Movie?");
		if(accpt){
			var url = BaseURL+"vote_dec_movies"
			$inde.ajax({
				type: "POST",
				url: url,
				//dataType: 'json',
				data: "movie_id="+movie_id,
				success: function(res){
					if(res == 0){
						alert('Voted successfully');
					}else{
						alert(res);
					}
				}
			});	
		}
		return false;
	}	
} 


//GET SITE URL
function getBaseURL() { 
	var url = location.href; 
	var baseURL = url.substring(0, url.indexOf('/', 14));  
	if (baseURL.indexOf('http://localhost') != -1) { 
		var url = location.href; 
		var pathname = location.pathname; 
		var index1 = url.indexOf(pathname); 
		var index2 = url.indexOf("/", index1 + 1); 
		var baseLocalUrl = url.substr(0, index2);  
		return baseLocalUrl + "/"; 
	} else { 
		return baseURL + "/"; 
	}  
}

//PREVENT KEY TYPE. FOR EXAMPLE: IF I TYPE DIGITS ONLY, WE USE THIS FUNCTION
function letternumber(e){ var key; var keychar;  if (window.event) key = window.event.keyCode; else if (e) key = e.which; else return true; keychar = String.fromCharCode(key); keychar = keychar.toLowerCase(); if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)) return true; else if((("0123456789").indexOf(keychar) > -1)) return true; else return false; }

// USED TO VALIDATE THE EMAILS
function isValidEmailAddress(emailAddress) {
	var emailreg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return emailreg.test(emailAddress);
}

function fbs_click() {
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

// function publish(title, desc, image, story_url){
function publish(title, desc,image, story_url){
	// alert(title);
	// alert(desc);
	// alert(image);
	// alert(story_url);
	// return false;
	FB.ui({	
		method: 'stream.publish',
		display: 'popup',
		message: '',
		attachment: {
			name: title,
			description: (desc),
			media: [{type:'image', src:BaseURL+'posters/soon.png', href:BaseURL+story_url}],
			href: BaseURL+story_url
		}
	},
		function(response) {
			// alert(response);
		}
	);
 }

