/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
$(document).ready(function(){
	// hide default text capcha
	if($('#recaptcha_instructions_image')) {
		 $('#recaptcha_instructions_image').hide();
	} 
	 if($('.recaptcha_only_if_incorrect_sol')) {
		 $('.recaptcha_only_if_incorrect_sol').hide();
	} 
	 if($('ul .errors')) {
		 $('ul .errors').hide();
	} 
    //Remove set homepage link for Chrome browser
    if(navigator.userAgent.indexOf('Chrome') != -1) {
        $("#setHomePage").remove();
    }
     
    $('.login-link').live('click', function() {
        showLoginForm();
        return false;
    });
    
    $('.auto-focus:first').focus();
    
    $('textarea.auto-hint').focus(function(){
        if($(this).val() == $(this).attr('title')){
            $(this).val('');
            $(this).removeClass('auto-hint');
        }
    });
    $('textarea.auto-hint').blur(function(){
        if($(this).val() == '' && $(this).attr('title') != ''){
           $(this).val($(this).attr('title'));
           $(this).addClass('auto-hint');
        }
    });
    $('textarea.auto-hint').each(function(){
        if($(this).attr('title') == ''){ return; }
        if($(this).val() == ''){ $(this).val($(this).attr('title')); }
        else { $(this).removeClass('auto-hint'); }
    });
    
    $("#login-username").keyup(function(event){
      if(event.keyCode == 13){
        $("#signin_submit").click();
      }
    });
    $("#login-password").keyup(function(event){
      if(event.keyCode == 13){
        $("#signin_submit").click();
      }
    });


});

function saveStuff(metaId, metaTitle, userId, type, link) 
{
    //Save stuff
    if ((metaId != "" || type == "other") && metaTitle != "" && userId != "" && type) {
        var linkSelf = "";
        if (type == "other") {
            linkSelf = "&link=" + escape(link);
        }
        $.ajax({
                type: "GET",
                url: "/stuff/save-stuff/",
                data: "id=" + metaId + "&title=" + encodeURIComponent(metaTitle) + "&uid=" + userId + "&type=" + type + linkSelf,
                success: function(html){
                    alert(html);
                }
        });
    }
}

function setAsHomePage(ob, url)
{
    if (document.all) {
        ob.style.behavior='url(#default#homepage)';
        ob.setHomePage(url);
    } else if (window.sidebar) {
        if(window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
                prefs.setCharPref('browser.startup.homepage',url);
                alert('Set SmartListing page as homepage successfully.')
            } catch(e) {
                alert("this action was avoid by your browser，if you want to enable，please enter about:config in your address line,and change the value of signed.applets.codebase_principal_support to true");
            }
        } 
    } else {
        alert('Not support for this browser.')
    }
}

function compare2Date(fromDate,endDate,strSplit)
{
	var from = $("#"+fromDate).val();
	if(from.length>0 &&from.length!=10){
		alert('From date invalid. Please check again.');
		$("#"+fromDate).focus();
		return false;
	}else if(from.length>0 &&from.length==10){
		var to = $("#"+endDate).val();
		if(to.length>0 &&to.length!=10){
			alert('To date invalid. Please check again.');
			$("#"+endDate).focus();
			return false;
		}else if(to.length>0 &&to.length==10){		
			var arrFromDate = from.split(strSplit);
			fromDate = new Date(arrFromDate[2], + arrFromDate[1], arrFromDate[0]);
			var arrToDate = to.split(strSplit);
			toDate = new Date(arrToDate[2], + arrToDate[1], arrToDate[0]);
			if(fromDate > toDate) {
				alert(' To Date must be greater than or equals to From Date. Please check again.');
				$("#"+endDate).focus();
				return false;
            }
			
		}		
		
	}
	
	return true;
}

function showLoginForm()
{
    $('html, body').animate({scrollTop:0}, 'fast');
    if (!$("#topnav .signin").hasClass('menu-open')) {
        $("#topnav .signin").click();
    }
    $('#signin-menu #login-username').focus();
}

function disableForm(form)
{
    $(form).find('input:submit, button').attr('disabled', 'disabled');
    $(form).find('input, textarea').attr('readonly', 'readonly');
}

function enableForm(form)
{
    $(form).find('input:submit,button').removeAttr('disabled');
    $(form).find('input, textarea').removeAttr('readonly');
}

/**
 * Check phone number when type
 * @param Object e Event object on form
 */
function checkFoneNum(e)
{
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;

	if(keycode==8 || keycode==0)
		keycode = 55;

	var keychar = String.fromCharCode(keycode);

	reg=new RegExp("[^0-9]");

	if(reg.test(keychar))
	{
		e.cancelBubble = true;
		e.preventDefault? e.preventDefault() : e.returnValue = false;
	}
}

/**
 * Find and Replace String
 * @param String haystack Original String
 * @param String find Search string
 * @param String sub String replace
 * @return String Replaced string
 */
function strReplace(haystack, find, sub) {
    return haystack.split(find).join(sub);
}

/**
* Strip whitespace (or other characters) from the beginning of a string
* @param String str String
* @param Char limit Char that you want to be stripped
*/
function lTrim(str, limit)
{
	n = limit.length
	while (str.substring(0,n)==limit)
	{
		str = str.substring(n,str.length)
	}
    return str
}

/**
* Strip whitespace (or other characters) from the end of a string
* @param String str String
* @param Char limit Char that you want to be stripped
*/
function rTrim(str, limit)
{
	n = limit.length
	while (str.substring(str.length-n,str.length+n)==limit)
	{
		str = str.substring(0,str.length-n)
	}
    return str
}

/**
* Strip whitespace (or other characters) from the beginning and end of a string
* @param String str String
* @param Char limit Char that you want to be stripped
*/
function Trim(str, limit)
{
	str = lTrim(str,limit)
	str = rTrim(str,limit)
	return str
}

/**
 * Set class CSS for object
 * @param String id Object ID
 * @param String classCSS Css class
 */
function setClassCSS(id, classCSS)
{
	document.getElementById(id).className = classCSS;
}

/**
 * Alert Message
 * @param String message Message
 */
function alertMessage(message)
{
	alert(message)
}

/**
 * Show tooltip in html element
 * @param string inputId
 * @param string message
 * @param string type in [error | load | pass]
 */
function showTooltip(inputId, message, type)
{
	$.validationEngine.buildPrompt($('#' + inputId), message, type);
}

/**
 * Hide tooltip
 * @param string inputId
 */
function hideTooltip(inputId)
{
	$.validationEngine.closePrompt($('#' + inputId));
}

/**
 * Return part of a string from the left n characters
 */
function leftStr(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

/**
 * Return part of a string from the right n characters
 */
function rightStr(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

/*
 * Add SubCategory
 */
function addSubCat(flagAlert)
{
	var catEl 				= $("#category option:selected")
		,catText 			= catEl.text()
		,subCatEl 			= $("#subcategory")
		,subCat 			= subCatEl.val()
		,subCatTextEl 		= $("#subcategory option:selected")
		,subCatText 		= subCatTextEl.text()
		,subCatAddedEl 		= $("#subcatadded")
		,subCatAdded 		= subCatAddedEl.val()
		,arrSubCatAdded 	= (subCatAdded? subCatAdded.split(',') : [])
		,countSubCatAdded 	= arrSubCatAdded.length
		,boxAddSubCatEl		= $("#boxAddSubCat");

	// sub category selected ??
	if (!subCat) {
        flagAlert = false;
		var n = $("#subcategory").attr('length');
        for(var i=1; i<n; i++) {
            $("#subcategory option[index="+i+"]").attr('selected', true);
            var result = addSubCat(flagAlert);
        }
        $("#subcategory option[index=0]").attr('selected', true);
        return;
	}


	// check sub category exist
	if (-1 != $.inArray(subCat, arrSubCatAdded)) {
		//return alertMessage(msgSubcateexisted);
        $("#subcategory option[index=0]").attr('selected', true);
        if (flagAlert) {
            alertMessage('Business Category existed!');
        }
        return 1;
	}

	// set value for sub category added element
	arrSubCatAdded.push(subCat);
	subCatAddedEl.val(arrSubCatAdded.join(','));

    // add a new row for box of sub category added
	var htmlNewRow = '<div id="boxCat_' + subCat + '"><p><span class="cat_added">'
			+ catText + '</span> &raquo; <span class="cat_added">'
			+ subCatText + '</span><span class="cat_remove" onclick=\'removeCat("' + subCat + '")\' style="cursor:pointer"> Remove</span></p></div>';

	var currentHtml = boxAddSubCatEl.html();
	boxAddSubCatEl.html(currentHtml + htmlNewRow);
}

/*
 * Remove subCategory from SubCategory Added
 * @param Integer subCat SubCategory removed
 */
function removeCat(subCat)
{
	var subCatAddedEl = $("#subcatadded")
		,subCatAdded = subCatAddedEl.val();

	if (!subCatAdded) {
		return window.alert('Invalid business category.');
	}

	var subCatAddedArray = subCatAdded.split(',');
	var index = $.inArray(subCat, subCatAddedArray);

	if (-1 === index) {
		return window.alert('Remove invalid business category.');
	}

	subCatAddedArray.splice(index, 1);
	subCatAddedEl.val(subCatAddedArray.join(','));
	$("#boxCat_"+subCat).remove();
}

function loadTinyMce(classControl){
    $('textarea.'+classControl).tinymce({
			// Location of TinyMCE script
			script_url : '/js/jquery/tinymce/jscripts/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "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 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			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 : "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"
			},
            relative_urls : false
		});
}

function loadTinyMceSimple(classControl){
    $('textarea.'+classControl).tinymce({
			// Location of TinyMCE script
			script_url : '/js/jquery/tinymce/jscripts/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,imagemanager",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,image,preview,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,|,fullscreen",
			theme_advanced_buttons4 : "",
			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 : "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",
			document_base_url : "articles/uploads/goc-ban-doc",
			documentBaseURL: "articles/uploads/goc-ban-doc",
			// Replace values for the template plugin
			template_replace_values : {
				username : "Some User",
				staffid : "991234"
			},
            relative_urls : false
		});
}

function loginAjax()
{
    
    var uname = $('#login-username').val();
    var pwd = $('#login-password').val();   
    var remember = $('#remember').val();
    if (uname == "" || pwd == "") {
        $('#login_message').html(login_invalid);
        return false;
    }
    $('#login_message').html('<img src = "/default/images/ajax_loading.gif"/>');

    disableForm($('#signin_menu form'));
    $.post("/login/process", {username: uname, password: pwd, remember_me: remember, ajax: 'true'},
       function(result){
           var abc = jQuery.parseJSON(result);
           if(abc.status == 'ok') {
               window.location.reload();
           } else {
              $('#login_message').html(abc.message);
              enableForm($('#signin_menu form'));
           }
       });
   return false;
}

// ads banner
$(document).ready(function(){
	var blocks = $('.ads-block');
	var adsBannerSlideIntervalMedia=0;
	var adsBannerSlideIntervalRight=0;
	var adsBannerSlideIntervalBotton =0;
	blocks.each(function(index, block) {
		adsBannerSlideInterval = $(block).attr("slideinterval")*1000;
		advtype = $(block).attr("advtype");
		var items = $(block).find('a.item');
		items.active = $(items[0]).show();
		if (items.length>1) {
			if(advtype == 'media'){
				adsBannerSlideIntervalMedia = adsBannerSlideInterval; 
				startSlideMedia(items);
			}
			if(advtype == 'right'){
				adsBannerSlideIntervalRight = adsBannerSlideInterval;
				startSlideRight(items);
			}
			if(advtype == 'botton'){
				adsBannerSlideIntervalBotton = adsBannerSlideInterval;
				startSlideBotton(items);
			}
			
		}
	});
	
	function startSlideMedia(items) {
		items.active = items.active.hide().next();
		if (!items.active.length) {
			items.active = $(items[0]);
		}
		//items.active.fadeIn(1500);
		items.active.show();

		setTimeout(function() {startSlideMedia(items);}, adsBannerSlideIntervalMedia);
	}
	function startSlideRight(items) {
		items.active = items.active.hide().next();
		if (!items.active.length) {
			items.active = $(items[0]);
		}
		//items.active.fadeIn(1500);
		items.active.show();
		
		setTimeout(function() {startSlideRight(items);}, adsBannerSlideIntervalRight);
	}
	function startSlideBotton(items,adsBannerSlideInterval) {
		items.active = items.active.hide().next();
		if (!items.active.length) {
			items.active = $(items[0]);
		}
		//items.active.fadeIn(1500);
		items.active.show();
		
		setTimeout(function() {startSlideBotton(items);}, adsBannerSlideIntervalBotton);
	}
});
var followClicked = false;
function followObject(id, type, div)
{
    if (userId == 0) {
        showLoginForm();
        return;
    }
    if (followClicked == false) {
        followClicked = true;
        jQuery.ajax({
          url: '/ajax/follow/id/' + id + '/type/'+ type,
          success: function(data) {
            $(div).html(followed_string);
            followClicked = false;
          }
        });
    }
}
function _pageArticleClick(Id, totalpage,uid) {
    $('#pageArticle').html('<img src="/theme/ebiv2/images/loading1.gif">');
    $('#pageArticle').show();
    for (i=1;i<=totalpage;i++){
    	//alert(i+'_'+Id);
    	if (i==Id){
    		
    		$('#box_'+i).addClass('active');    		
    	}else{    		
    		$('#box_'+i).removeClass('active');
    	}  	
    }   
    $.ajax({
        type: 'POST',
        url:  '/ajax/list-article',
        data: {'page': Id,'uid':uid},
        success: function(strHTML){
            $('#pageArticle').hide();
            $('#pageArticle').html(strHTML);
            $('#pageArticle').fadeIn(1000);
        }
    });
    
    
}

