// JavaScript Document
var CMSROOTPATH = 'http://'+window.location.host; 
//var ROOTURLPATH = "http://seems.technoholik.com/frontend/";
var ROOTURLPATH = "http://"+window.location.host+"/";
var TODBFILEPATH = CMSROOTPATH+'/2db';

/**** To Validate Email Address*********/
function isValidEmail(str) {
				emailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?(\w)+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/

		if (!emailRe.test(str))	
			return false	
		else
			return true				
}

/**** To Validate If the given string is a valid URL*********/
function isValidURL(url){
    var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if(RegExp.test(url)){
        return true;
    }else{
        return false;
    }
}
/**** To Validate If the given string contains only Alphabets & Numbers, nothing else*********/
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);
}
/**** To Validate If the given string contains only Numbers, nothing else*********/
function isNumeric(str)
	{
		var bReturn = true;
		var valid="0123456789+- ";
		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);
	}
/**** To Remove the Deleted div*********/
function removeDiv(success){
	var jObj=eval("("+success+")"); //alert(success);
	
	if(jObj.status==1){
		var divID = "singleCont"+jObj.id;		// alert("DIVid="+divID);
		$('#'+divID).fadeOut('slow');
	}
	$("#notification").html('');
	$("#notification").html(jObj.msg);
	setTimeout(function(){ $('#notification').fadeOut('slow'); }, 3000);	//---Notification will fade out in 3 seconds
	if(jObj.numRecords == 0){		//------------If it is a last record then show "NO Records"
		$("#mainContainer").html('<div id="norecordsdiv" class="h1tdB1">NO RECORDS</div>');	
	}
}
/********  TRIM LEFT FUNCTION ******************/
function lTrim(str)
{
  var whitespace = new String(" \t\n\r");

  var s = new String(str);

  if (whitespace.indexOf(s.charAt(0)) != -1) {
    // We have a string with leading blank(s)...

    var j=0, i = s.length;

    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
    j++;

    s = s.substring(j, i);
  }

  return s;
}
/****** TRIM RIGHT FUNCTION ****************/
function rTrim(str)
{
 
  var whitespace = new String(" \t\n\r");

  var s = new String(str);

  if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
    var i = s.length - 1;       // Get length of string

    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
      i--;

    s = s.substring(0, i+1);
  }

  return s;
}
/**********   TRIM FUNCTION **********************************/
function Trimnew(str)
{
  return rTrim(lTrim(str));
}

function strrev( string ){
  
  	var ret = '', i = 0;
    string += '';
    for ( i = string.length-1; i >= 0; i-- ){
       ret += string.charAt(i);
    }

    return ret;
}

/******** Function to check cookie value ******************/
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 to set cookie **************************/
function Set_Cookie( name, value, expires, path, domain, secure ){		//alert('name='+name+' value='+value);
		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 : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
	}
/******** Function to Open/Close DropDowns Ends **********************************/
function strpos( haystack, needle, offset){
    // Finds position of first occurrence of a string within another  
    var i = (haystack+'').indexOf( needle, offset ); 
    return i===-1 ? false : i;
}
function redirect(URLStr) { location = URLStr; }

function processCommentForm() {
	var flag = 0;		
	var	errmsg = "";
	var commentUserName	= Trimnew($("#commentUserName").val());
	var commentPassword = Trimnew($("#commentPassword").val());
	var commentText = Trimnew($('#commentText').val());
	var captchastring0 = Trimnew($('#captchastring0').val());
	
	if(commentUserName == "")
	{
		errmsg	+=	"Please enter your Username<br>";
		$('#commentUserName').focus();
		flag = 1;
	}
	if(commentPassword == "")
	{
		errmsg	+=	"Please enter your Password<br>";
		$('#commentPassword').focus();
		flag = 1;
	}
	if(commentText == "" || commentText == "Comments")
	{
		errmsg	+=	"Please enter your Comment<br>";
		$('#commentText').focus();
		flag = 1;
	}	
	if(captchastring0 == "")
	{
		errmsg	+=	"Please enter Security code<br>";
		$('#captchastring0').focus();
		flag = 1;
	}	
	
	if(errmsg!="")
	{
		$('#showerrorComment').html('');
		$('#showerrorComment').show();
		$('#showerrorComment').html(errmsg);		
	}
	
	
	if(flag == 0)
	{
		var datastring	=	 $('#frmCommentBox').serialize();
		//alert(datastring);
		$.ajax({
			type: "post",
			url: TODBFILEPATH+"/comment2db.php",
			data: datastring,
			success: function(data)
			{
				//alert(data);
				if(data ==1){
						$('#frmCommentBox').hide();						
						$('#commentBoxRes').show();
				} else if(data ==3){
						$('#showCommenterrorReturn').html("Please enter correct Security code.");
						$('#showCommenterrorReturn').show();
				} else {
						$('#showCommenterrorReturn').html("Please enter correct Security code.");
						$('#showCommenterrorReturn').show();
				}
			}
		});
	}
}

function processSearch() {
	searchTags = $('#searchTags').val();
	
	/*if (searchTags == '') {
		alert("Please enter Search term.");
		return false;
	} else {*/
		location.href = ROOTURLPATH+'search.html?tags='+searchTags;
		return false;
	//}
}

function newletterpopup(){
	showNewsletterDiv();
	$('html, body').animate({scrollTop: $("#newsLetter").offset().top}, 2000);
}

//Functio for posting the querys from expert page
function postthequestion(){
	var userquerry	= $("#userquerry").val();
	var username	= $("#username").val();
	var useremail	= $("#useremail").val();
	var expert_id	= $("#expert_id").val();
	var sectionid	= $("#section_id").val();
	var paginationurl=$("#paginationurl").val();
	var isanonymous	= $('#isanonymous').attr('checked');
	var readedtnc	= $('#readedtnc').attr('checked');	
	var flag=0;
	if(userquerry == ''){
		errmsg	=	"Please Enter Your Querry";
		$('#userquerry').focus();
		flag=1;
	}else if(username == ''){
		errmsg	=	"Please Enter Your Name";
		$('#username').focus();
		flag=1;
	}else if(username == ''){
		errmsg	=	"Please Enter Your Name";
		$('#username').focus();
		flag=1;
	}else if(useremail == ''){
		errmsg	=	"Please Enter Your Email-Id";
		$('#useremail').focus();
		flag=1;
	}else if (!isValidEmail(useremail)){
			errmsg	=	"Please Enter Valid Email Address";
			$('#useremail').focus();
			flag=1;
	}else if(readedtnc == false){
		errmsg	=	"Please Select Trems & Condition";
		//$('#readedtnc').focus();
		flag=1;
	}
	 if(isanonymous == false){
	 	isanonymous=0;
	 }else{
		isanonymous=1;	
	 }
	if(flag==0){ //alert("asda");
				$.post(TODBFILEPATH+"/askexpert2db.php",{'userquerry':userquerry,'username':username,'useremail':useremail,'expert_id':expert_id,"readedtnc":"1","isanonymous":isanonymous,'sectionid':sectionid},function(data){ //alert(data);
				 
				 if(Trimnew(data)=='BadWord'){
					$("#showerrorComment").html('Beep Beep mind your language.');
					$("#showerrorComment").show();
				 } else {
					 $("#showerrorComment").html('');
					 $("#commentBoxRes").show();
					 $("#userquerry").val('');
					 $("#username").val('');
					 $("#useremail").val('');
					$.post("http://revampstg.idiva.com/tplGetExpertUnasweredDiv.php",{"id":expert_id,"paginationurl":paginationurl},function(data){ //alert(data);
						 $("#unanswered").html(data);
  				    });	
				}
		});
	}else{
		  	$("#showerrorComment").html(errmsg);
		  	$("#showerrorComment").show();
	}
}


// Function for posting the comments from article page
function postthecomment(){
	var comment_text = $("#comment_text").val();
	//var comment_parentid = $("#comment_parentid").val();
	var content_id       = $("#content_id").val();
	 $("#showerrorComment").hide();
	 $("#commentBoxRes").hide();
	if($("#whichusertype").val()=='1'){
			var first_name = $("#first_name").val();
			var whihcflag = $("#whichcontype").val();
			var last_name = $("#second_name").val();
			var screenName = $("#userscreenname").val();
			var profile_url = $("#userprofilelink").val();
			var profileImage = $("#userprofileimage").val();
			var loginusertypeid = $("#loginusertypeid").val();
			$.post(TODBFILEPATH+"comment2db.php",{'login_type':'facebook','first_name':first_name,'whihcflag':whihcflag,'last_name':last_name,'screenName':screenName,'profile_url':profile_url,'profileImage':profileImage,'loginusertypeid':loginusertypeid,'comment_text':comment_text,"content_id":content_id,"comment_parentid":comment_parentid},function(data){ 
			        $("#commentBoxRes").show();
			});


				
					var message = comment_text;
					var article_title = "<?=$cTitle?>";
					var article_page_link = "<?=$main_URL?>";
					var story_section ="<?=$STORY_SECTION?>";
					var story_section_url ="<?=$STORY_SECTION_URL?>";			
					var author_name = "<?=$AUTHOR_NAME?>";
					var author_name_url = "<?=$AUTHOR_URL?>";
					var posteddate = "<?=$POSTEDON?>"
					var article_image_path ="<?=$STORY_THUMNAIL?>";
					var attachment = {'name': article_title, 'href': article_page_link ,'properties' : 
						{
						'Filed under': {'text': story_section, 'href':  story_section_url},
						'Author '    : {'text': author_name, 'href':author_name_url},
						'Posted On': posteddate}
						,'media': [{ 'type': 'image', 'src': article_image_path, 'href': article_page_link }] }; 				
					var action_links = [{'text':'Technokolic', 'href':'http://www.technoholik.com/'}];
					FB.Connect.streamPublish(message, attachment, action_links); 


			/*var article_title = "<?=$cTitle?>";
			var message = comment_text;
			//----------Image of the article
			var est_image_path ="";
			var category_of_the_artice = "Mobile";
			var category_of_the_artice_link ="http://www.technoholik.com/";
			var pagelinkfromfb = location.href;
			if(est_image_path==""){
				var est_image_path ="http://seems.technoholik.com/frontend/images/logo.gif";
			}
			var attachment = { 'name': article_title, 'href': pagelinkfromfb ,'properties': { 'Type ': { 'text': category_of_the_artice, 'href':  category_of_the_artice_link}}, 'media': [{ 'type': 'image', 'src': est_image_path, 'href': pagelinkfromfb }] }; 
			var action_links = [{'text':'Times Food Guide', 'href':'http://www.timescity.com/'}];
			FB.Connect.streamPublish(message, attachment, action_links); */
			
			
	}else{
		//var useremail = $("#Username").val();
		//var userpassword = $("#Password").val();
		var username= $("#Username").val();
		var useremailid= $("#Useremail").val();
		var comment_parentid=$("#comment_parentid").val();
		var userpassword=$("#Password").val();
		var content_id=$("#content_id").val();
		var whihcflag = $("#whichcontype").val();
		var flag = 0;
		if(comment_text==""){
			errmsg	=	"Please Enter Your Comment";
			$('#comment_text').focus();
			flag=1;
		}else if(username==""){
			errmsg	=	"Please Enter Your Name";
			$('#Username').focus();
			flag=1;
		}else if(useremailid==""){
			errmsg	=	"Please Enter Your Email ID";
			$('#Useremail').focus();
			flag=1;
		}else if (!isValidEmail(useremailid)){
			errmsg	=	"Please Enter Valid Email Address";
			$('#Useremail').focus();
			flag=1;
		}else if (userpassword	==	"" || userpassword	==	"Password"){
			errmsg	=	"Please Enter Password";
			$('#Password').focus();
			flag=1;
		}
		if(flag==0){ //alert("asda");
				$.post("http://revampstg.idiva.com/2db/comment2db.php",{'login_type':'normaluser','EmailId':useremailid,'whihcflag':whihcflag,'Username':username,"userpassword":userpassword,"content_id":content_id,"comment_parentid":comment_parentid,'comment_text':comment_text},function(data){
				 if(data=='error'){
				   $("#showerrorComment").html('User and password did not match.');
				   $("#showerrorComment").show();
				 }else{
				    $("#commentBoxRes").show();
				    $.post("http://revampstg.idiva.com/tplGetcommentadded.php",{"content_id":content_id,"pageval":"1"},function(data){ //alert(data);
						 $("#showcommentcontent").html(data);
						  $("#commentBoxRes").show();
						 
						 $("#Username").val('');
						$("#Useremail").val('');
						$("#comment_text").val('');
  				    });
				 }
			});
		}else{
		  $("#showerrorComment").html(errmsg);
		  $("#showerrorComment").show();
		}
	}
}
//added by Manish
function clearForm(form)
{document.getElementById(form).reset(); $('#frmResponderBox').html('');}

function showErrorMsg(errmsg,errBox,anim)
{
	$('#'+errBox).html('');
	$('#'+errBox).show();
	$('#'+errBox).html(errmsg);
	if(anim===true){$('html, body').animate({scrollTop:$("#"+errBox).offset().top},1000);}
}

String.prototype.ucfirst = function()
{
    return this.charAt(0).toUpperCase() + this.substr(1);
}

// Function for get Comments
function showPagingComment(contentId, pageNo,whichflag){
	
	$("#showcommentcontent").html("Loading...");
	
	 $.post(ROOTURLPATH+"tpl/tplGetcommentadded.php",{"id":contentId,"pg":pageNo},function(data){ 
		 $("#showcommentcontent").html(data);
                  var nocomments = $('#nocomments_'+contentId).val();
		//console.debug(nocomments);
		
		if( nocomments > 0){
			$('#comment_'+contentId).html('');
			$('#comment_'+contentId).html('<a href="#landcomment" title="'+nocomments +'  Comments">'+nocomments +'  Comments </a>' );
		}
	});
}

// Function for view count
function updateViewCnt(id,sid,photo_id,datafrm){                             
                                 
	$.post(TODBFILEPATH+"/updateviewcount.php",{'id':id,'sid':sid,'photo_id':photo_id,'datafrm':datafrm},function(data){
                 var name = new Array();                                               
                 name[0] = 'view';
                 if(datafrm == 'comment')
                      name[1] = datafrm;      
                 //  console.debug(jQuery.trim(data));
                if(jQuery.trim(data) != '' && jQuery.trim(data)!=null ){
                     var resultArray = eval("("+data+")");
                    // console.debug(resultArray);
                    //  console.debug(resultArray.view.length);
                      for( k=0; k < name.length; k++){
                              
                               // console.debug(eval(resultArray[name[k]].length));
                            if(jQuery.trim(resultArray[name[k]]) != '' && jQuery.trim(resultArray[name[k]])!=null   ){
                                   for( i=0; i < resultArray[name[k]].length; i++){
                                        //   console.debug('#'+name[k]+'_'+resultArray[name[k]][i].contentId);
                                           var viewid = '#'+name[k]+'_'+resultArray[name[k]][i].contentId;
                                       //    var colName = ( name[k] == 'comment')?'CommentCNT':'iViewCount';
                                           if( name[k] == 'comment'){
                                               $(viewid).html('').html(resultArray[name[k]][i]['CommentCNT'] +' '+ name[k].ucfirst()+'s' );                                            
                                           }
                                           else{
                                               $(viewid).html('').html('<div class="b_11 views PA6">'+resultArray[name[k]][i]['iViewCount'] +' Views</div>' );                                                
                                           }
                                     }                            
                                     
                                }
                       }
                }
	});
}

$(window).bind("load", function() {  
  var rndtno = Math.random();
  $('#timeslog').attr('src', 'http://timeslog.luxpresso.com/timeslog.dll/topcnt?CHUR=luxpresso.com&randomno='+ rndtno);
  
  var timeout = setTimeout(function() {
    $('.lazyload1second').each(function(){
      $(this).attr('src', $(this).attr('original_link'));
    });
  }, 1000);

  var timeout1 = setTimeout(function() {
    $('.lazyload2second').each(function(){
      $(this).attr('src', $(this).attr('original_link'));
    });
  }, 2000);

  var timeout2 = setTimeout(function() {
    $('.lazyload3second').each(function(){
      $(this).attr('src', $(this).attr('original_link'));
    });
  }, 3000);
  
  $.getScript('http://apis.google.com/js/plusone.js', function() {});    
  
  $(".facebook_share").each(function(index) {
      // alert(index + ': ' + $(this).text());
       var fb_share_url = $(this).find(":input").attr("value");
     
       $(this).append('<iframe src="'+fb_share_url+'" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:90px; height:21px;" allowTransparency="true"></iframe>');
      //  console.debug($(this));
      // $(this).find(":iframe").attr("src", fb_share_url);     
  });
 });
