/* Custome functons here*/

function addEvent(obj, evType, fn)
{
	if (obj.addEventListener)
	{
		obj.addEventListener(evType, fn, false);
		return true;
	}
	else if (obj.attachEvent)
	{
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	}
	else
	{
		return false;
	}
}

addEvent(window, "scroll", centerPopWindow);
window.onscroll = centerPopWindow;

function centerPopWindow()
{
	jQuery(".window-container").each(function(){
		
		frmwidth=$(this).css('width').replace('px','');
		frmheight=$(this).css('height').replace('px','');
		
		
		var winW = window.innerWidth;
		var positionX=(winW-frmwidth)/2;
		
		var winH = window.innerHeight;
		var posY=(winH-frmheight)/2;
		var scrollH=getScrollTop();
		for(var i=0; i<=scrollH; i++)
		{
		positionY=parseInt(i)+parseInt(posY);
			
		//$(this).css('left',positionX);
		$(this).css('top',positionY);
		}
		
	});
}


function calliframe(eid,winname,filename,frmwidth,frmheight)
{
	var chkOpenWindow=true;
	jQuery(".window-container").each(function(){
		if($(this).attr("id")==eid)
			chkOpenWindow=false;
	});
	
	var titlenamearr=winname.split('-');
	
	if(titlenamearr.length>1)
	{
		var titlename="";
		
		for(var i=0;i<(titlenamearr.length-1);i++)
		{
			titlename+=titlenamearr[i];
			if(i!=(titlenamearr.length-2))
				titlename+="-";
		}
		titlename=titlename.substr(0,25);		
		winname=titlename+ " - " + titlenamearr[titlenamearr.length-1];
	}
	
	if(chkOpenWindow)
	{
		
		if((navigator.userAgent.match(/iPad/i)) || navigator.userAgent.match(/iPhone/i)) {
		window.open(filename,eid,"menubar=0,resizable=1,width="+frmwidth+",height="+frmheight+",toolbar=1,scrollbars=yes");
		}
		else
		{
			var winW;
			var winH;
			
			if ('innerWidth' in window) {   // all browsers, except IE before version 9
				winW=window.innerWidth;
			}
			else {  // Internet Explorer before version 9
				winW=document.documentElement.clientWidth;
			}
			
			if ('innerHeight' in window) {  // all browsers, except IE before version 9
				winH=window.innerHeight;
			}
			else {  // Internet Explorer before version 9
				winH=document.documentElement.clientHeight;
			}
			
			var positionX=(winW-frmwidth)/2;
			var posY=(winH-frmheight)/2;
			var scrollH=getScrollTop();
			positionY=scrollH+posY;
			
			jQuery.newWindow({id:eid,posx:positionX,posy:positionY,width:frmwidth,height:frmheight,title:winname, type:"iframe"});
			jQuery.updateWindowContent(eid,'<iframe src="'+filename+'" width="'+frmwidth+'" height="'+frmheight+'"  style="border:0px" />');
		}
	}
}

function callForAjax(eid,winname,filename,frmwidth,frmheight,functionname)
{
	var chkOpenWindow=true;
	jQuery(".window-container").each(function(){
		if($(this).attr("id")==eid)
			chkOpenWindow=false;
	});
	
	var titlenamearr=winname.split('-');
	
	if(titlenamearr.length>1)
	{
		var titlename="";
		
		for(var i=0;i<(titlenamearr.length-1);i++)
		{
			titlename+=titlenamearr[i];
			if(i!=(titlenamearr.length-2))
				titlename+="-";
		}
		titlename=titlename.substr(0,25);		
		winname=titlename+ " - " + titlenamearr[titlenamearr.length-1];
	}
	
	if(chkOpenWindow)
	{
		var winW;
		var winH;
		
		if ('innerWidth' in window) {   // all browsers, except IE before version 9
			winW=window.innerWidth;
		}
		else {  // Internet Explorer before version 9
			winW=document.documentElement.clientWidth;
		}
		
		if ('innerHeight' in window) {  // all browsers, except IE before version 9
			winH=window.innerHeight;
		}
		else {  // Internet Explorer before version 9
			winH=document.documentElement.clientHeight;
		}	
		
		var positionX=(winW-frmwidth)/2;
		
		var posY=(winH-frmheight)/2;
		var scrollH=getScrollTop();
		positionY=scrollH+posY;
		
		
		jQuery.newWindow({id:eid,posx:positionX,posy:positionY,width:frmwidth,height:frmheight,title:winname});
		jQuery.updateWindowContentWithAjax(eid,filename,false,functionname);
	}
}


function getScrollTop() {
	if (self.pageYOffset) // all except Explorer
	{
		return self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		return document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		return document.body.scrollTop;
	}
}

function ValidateLogin(formName,valGroup)
{	
	if(eval(getFormElement(formName,valGroup)))
	{
		showLoadingModal();
		jQuery.ajax({
			type		: "POST",
			cache	: false,
			url		: BASE_URL+"login_action.php",
			data		: jQuery("#loginFormFancybox").serializeArray(),
			dataType : 'json',
			success: function(data) { 				
				if(data.error=='Invalid login details'){
					jQuery('#error_message').html(data.error);
					}else{
				jQuery(window.location).attr('href', BASE_URL);
				}
				hideLoadingModel();
			}
		});
	}
}

function ValidateComments(formName,valGroup)
{	
	if(eval(getFormElement(formName,valGroup)))
	{
		document.commentFormFancybox.submit();
	}
}

function CommentsPopUp(toprateval)
{
	var listid=jQuery("#listid").val();
	
	var category_id=jQuery("#category_id").val();
	
	if(listid)
	{
		jQuery("#rec_"+listid).css({'border' : 'none'});
	}
	tinymcEditor();

	jQuery("#commentFormFancybox").bind("submit", function() {


		jQuery.ajax({
			type		: "POST",
			cache	: false,
			url		: BASE_URL+"comments_action.php",
			data		: jQuery(this).serializeArray(),
			dataType : 'json',
			success: function(data) {	
					
					jQuery('#ullistcomments').html(data.htmldata);
					
					var commentCount=jQuery('#lblcommentcounter'+data.listid).html();
					commentCount++;
					jQuery('#lblcommentcounter'+data.listid).html(commentCount);
					
					jQuery('#comment_error_message').html(data.msg);
					jQuery('#txtcomments').val('');
			}
		});
	
		return false;
	  });
	
}


function SendMessagePopUp()
{
	tinymcEditor();
	
	jQuery("#sendmsgFormFancybox").bind("submit", function() {

		jQuery.ajax({
			type		: "POST",
			cache	: false,
			url		: BASE_URL+"sendmessage_action.php",
			data		: jQuery(this).serializeArray(),
			dataType : 'json',
			success: function(data) { 
				jQuery('#comment_error_message').html(data.msg);					
				jQuery('#txtsubject').val('');
				jQuery('#txtmessage').val('');
			}
		});
	
		return false;
	  });
		
}

function ValidateForgotPassword(formName,valGroup)
{	
	if(eval(getFormElement(formName,valGroup)))
	{
		showLoadingModal();
		jQuery.ajax({
			type		: "POST",
			cache	: false,
			url		: BASE_URL+"account_action.php",
			data		: jQuery("#password_form").serializeArray(),
			dataType : 'json',
			success: function(data) { 				
				if(data=='0')
				{
					jQuery('#login_error').html('Your email address not found in our database!');
					jQuery('#login_error').attr("style","color:#ff0000;");
				}
				else
				{
					jQuery('#login_error').html('New password has been sent successfully!');
					jQuery('#login_error').attr("style","color:#009900;");
				}	
				hideLoadingModel();
			}
		});
	}
}

function ShowProfileDiv(ancObjId,divId)
{
	jQuery("#profile #user_tab a").removeClass('active');
	jQuery('#'+ancObjId).attr('class', 'active');
	
	if(document.getElementById("usertype").value==2)
		document.getElementById("basicinfo").style.display='none';
	else if(document.getElementById("usertype").value==3)
		document.getElementById("corpinfo").style.display='none';
		
	document.getElementById("changepass").style.display='none';	
	document.getElementById("profilesetting").style.display='none';
	document.getElementById("top10market").style.display='none';
	document.getElementById("frndsetting").style.display='none';
	
	document.getElementById(divId).style.display='';
}

function ShowSearchEmailDiv(ancObjId,divId)
{
	jQuery("#searchemail #user_tab a").removeClass('active');
	jQuery('#'+ancObjId).attr('class', 'active');
	
	document.getElementById("searchfrnd").style.display='none';
	document.getElementById("emailfrnd").style.display='none';
	document.getElementById("error_message").style.display='none';
	document.getElementById(divId).style.display='';
}

function getShareFriendId(rdbFriendObj)
{
	jQuery("#friend_id").val(rdbFriendObj.value);
}

function tinymcEditor()
{
	
		$('textarea.tinymce').tinymce({
			// Location of TinyMCE script
			script_url : BASE_URL+'jscripts/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,forecolor,backcolor,fontselect",
			theme_advanced_buttons2 : "",
			//theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			//theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,

			// Example content CSS (should be your site CSS)
			content_css : BASE_URL+"css/content.css",

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js",

			// Replace values for the template plugin
			template_replace_values : {
				username : "Some User",
				staffid : "991234"
			}
		});
		
}
function ShowStarRating(divid,hidrateId,divnum,cval,allowrating)
{ 
	if(!cval)
		cval=0;
	$('#'+divid+divnum).rating('rating_action.php', {maxvalue:5,increment:.5,starid:divnum,curvalue:cval,allowrating:allowrating,rateId:hidrateId});
}

function getMyMsg(inoutval,msgId)
{
	// POST DATA

	showLoadingModal();
	jQuery.post("mymessagetext.php", {inoutval:inoutval,msgId: msgId}, function(response){
		jQuery('#divinoutmsg').css({'display':'none'});
		jQuery('#divmsg').css({'display':''});
		jQuery('#divmsg').html(response);
		xval.remove();
	});	
}

function getInOutMsg(inoutval,recId,msgId)
{
	// POST DATA
	showLoadingModal();
	jQuery('#divinoutmsg').css({'display':''});
	jQuery('#divmsg').css({'display':'none'});
	
	var msgPname="mymessageinout.php";
	if(inoutval==4)
	{
		msgPname="sendmessage.php";
	}
	
	if(!recId)
		recId='';
	
	if(!msgId)
		msgId='';
		
	
	jQuery.post(msgPname, {inoutval: inoutval,recid:recId,msgid:msgId}, function(response){
		jQuery('#divinoutmsg').html(response);
		
		if(inoutval==4)
			SendMessagePopUp();
		
		xval.remove();
	});
	
	
}



function getTop10(tab)
{
	// GET CATEGORY ID OF FIRST
	var category = '';
	category = jQuery("#slideshow li:first-child").attr("id");
	category = category.split("_")[1];
	
	// SELECTED TAB
	jQuery("#user_tab a").each(function(index, domEle){
		alt = jQuery(this).attr('class', '');
	})
	jQuery('#'+tab+'').attr('class', 'active');
	
	// POST DATA	
	jQuery.post("tab_action.php", {task: 'get_tab',tab: tab,category: category}, function(response){
		jQuery('#top10_choiceof_users').html(response);																	
	});
}

function setCatImgByMyTop(chkIndex)
{
	/*if(chkIndex==1 && document.getElementById("use_cat_image").checked)
	{
		document.getElementById("def_cat_image").checked=false;
		document.getElementById("no_cat_image").checked=false;
	}
	if(chkIndex==2 && document.getElementById("def_cat_image").checked)
	{
		document.getElementById("use_cat_image").checked=false;
		document.getElementById("no_cat_image").checked=false;
	}
	if(chkIndex==3 && document.getElementById("no_cat_image").checked)
	{
		document.getElementById("use_cat_image").checked=false;
		document.getElementById("def_cat_image").checked=false;
	}*/
	
	if(chkIndex==3 && document.getElementById("no_cat_image").checked)
	{
		document.getElementById("use_def_cat_image").checked=false;
	}
	if(chkIndex==4 && document.getElementById("use_def_cat_image").checked)
	{
		document.getElementById("no_cat_image").checked=false;
	}
}

/*function chkEmbededCode()
{
	if(document.getElementById("embededcode").checked)
	{
		document.getElementById("txtembededcode").disabled=false;
		document.getElementById("listlink").disabled=true;
	}
	else
	{
		document.getElementById("txtembededcode").disabled=true;
		document.getElementById("listlink").disabled=false;
	}
}*/

function chkEmbededCode(counter)
{
	if(document.getElementById("embededcode"+counter).checked)
	{
		document.getElementById("txtembededcode"+counter).style.display='';
		//document.getElementById("listlink"+counter).style.display='none';
	}
	else
	{
		document.getElementById("txtembededcode"+counter).style.display='none';
		document.getElementById("listlink"+counter).style.display='';
	}
}

function chkProfileEmbededCode()
{
	if(document.getElementById("embededcode").checked)
	{
		document.getElementById("divembededcode").style.display='';
		document.getElementById("divvideo").style.display='none';
	}
	else
	{
		document.getElementById("divembededcode").style.display='none';
		document.getElementById("divvideo").style.display='';
	}
}

function setTop10(tab,id,dbclick)
{
	// GET CATEGORY ID OF FIRST
	var category = '';
	/*
	category = jQuery("#slideshow li:first-child").attr("id");
	category = category.split("_")[1];
	*/
	category = id;
	// SELECTED TAB
	jQuery("#user_tab a").each(function(index, domEle){
		alt = jQuery(this).attr('class', '');
	})
	jQuery('#'+tab+'').attr('class', 'active');
		
	// POST DATA	
	jQuery.post("tab_action.php", {task: 'get_tab',tab: tab,category: category,dbclick: dbclick}, function(response){
		jQuery('#top10_choiceof_users').html(response);																	
	});
}

function getListing(tab,cid,dbclick)
{ 

//alert(tab+'  '+cid+'  '+dbclick);
	var selected_tab =  '';
	selected_tab = jQuery("#user_tab a.active").attr("id");
	if(selected_tab =='setup_mytop10' || selected_tab=='friendstop10')
	{ 
		setTop10(selected_tab,cid,'');
	}
	else if(selected_tab =='top10' || selected_tab =='mytop10')
	{
		setTop10(selected_tab,cid,dbclick);
		
	}else if(selected_tab =='setup_my_category'){
		getTop10(selected_tab);
	}else{
		
		}

}

//////////////////////////////////////////////////////////////////////
//SET UP TOP 10
/////////////////////////////////////////////////////////////////////


function checkUploadedFileExtension(obj)
{
	//var va = document.forms['frmbook1'].elements['no_of_persons'].value;
/*var extension = new Array(".jpg",",jpeg",".JPG",".JPEG",".gif",".GIF",".png",".PNG");
var i,c=0 ;
alert("extension.length= "+extension.length);
for(i =0; i<  extension.length; i++ )
{alert('i= '+i);
alert(document.forms[obj].elements['file'].value.lastIndexOf(extension[i]));
if((document.forms[obj].elements['file'].value.lastIndexOf(extension[i]) == -1))
{
 alert("Files must be either JPG, JPEG, GIF, or PNG and less than 10,000 kb !");
 c = i;
 i = extension.length;
 }
 if(c< i)
 {return true;}
 else {return false;}
}*/
return true;
}


//////////////////////////////////////////////////////////////////////
//SET UP TOP 10
/////////////////////////////////////////////////////////////////////

function delete_items(obj,action,id)
{
//alert(action);
//alert(obj);
//alert(id);
	var form_name = obj;
	// POST DATA	
	jQuery.post("delete_items.php", {task: 'items',action: action,id: id}, function(response){
    //alert(response);
	var parent_id = document.getElementById('itemList');
	var child_id = document.getElementById('rec_'+id);
	parent_id.removeChild(child_id);
	jQuery('#d_message').html(response);
	var catId = document.getElementById('category_id').value;
	var catName = document.getElementById('category_name').value;
	getListing('setup_mytop10',catId, catName);
	});
}

function addnew_category(obj)
{
	if(obj == 'add'){
		document.getElementById("addnew_category").style.display ='';
		jQuery("#ancaddnewup").removeClass('anctag');
		jQuery('#ancaddnewup').attr('class', 'anctagactive');
		jQuery("#ancaddnewdown").removeClass('anctag');
		jQuery('#ancaddnewdown').attr('class', 'anctagactive');
		
	}
	if(obj.value == 'Cancel'){
		document.getElementById("addnew_category").style.display ='none';
		jQuery("#ancaddnewup").removeClass('anctagactive');
		jQuery('#ancaddnewup').attr('class', 'anctag');
		jQuery("#ancaddnewdown").removeClass('anctagactive');
		jQuery('#ancaddnewdown').attr('class', 'anctag');
	}
}

function delay(seconds)
{
	var currentTime= new Date();
	
	var currentSystemSeconds= null;
	currentSystemSeconds= currentTime.getSeconds();
	var estimatedTime= eval(currentSystemSeconds+seconds);

	while ( currentSystemSeconds< estimatedTime)
	{
		var currentTime= new Date(); 
		currentSystemSeconds= currentTime.getSeconds();
	}
}

function generateAccessCode()
{
	showLoadingModal();
	var response = 	generate_random_string(6);
	jQuery('#access_code').attr('value', response );																
	hideLoadingModel();
	// POST DATA	
	/*jQuery.post("generate_access_code.php", {task: 'generate_access_code'}, function(response){
		jQuery('#access_code').attr('value', response );																
		hideLoadingModel();
	});*/
}

function showAccessCode(access_code_required){
	if(access_code_required.checked)
	{
		document.getElementById('access_code_row').style.display='';
		if(document.getElementById('access_code').value=='')
			generateAccessCode();
	}else{
		document.getElementById('access_code_row').style.display='none';
		}
}

function generate_random_string(length)
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for( var i=0; i < length ; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

