//by hugo

function klg_changeInput(options){
    
    var defaults = {
        hasValue :true,//是否将文本的值写入input
        hasBlur : true//文本框是否需要获取焦点
    }
    
    var settings = $.extend({}, defaults, options);
//    console.info(defaults,options,settings);
    
    var element = settings.element;
    var tdText;
    if(!settings.attr){
        tdText = element.text();
    }
    else{
        tdText = element.attr(settings.attr);
    }
    
    element.empty();
    var input = $("<input />");
    

    if (settings.hasValue){
		input.attr("value", tdText);
	}
    
    for (var param in settings.params) {
        input.attr(param, settings.params[param]);
    }
    element.append(input);
    input.keyup(function(event){
        var myEvent = event || window.event;
        var keyCode = myEvent.keyCode;
        if (keyCode == 27) {
            input.val(tdText);
        }
    });
	if (settings.hasBlur) {
        input[0].select();
    }
    element.unbind("click");
}

/***
 * change text to select
 * @param {jquery Object} handleObject
 * @param {string} selectName 
 * @param {json} jsonData :json format.eg: "D":"Letter D","E":"Letter E","F":"Letter F","G":"Letter G"
 */
function klg_changeSelect(handleObject,jsonData,selectClass){
    var labelHtml = handleObject;
    var textValue = labelHtml.text();	
    labelHtml.empty().html("&nbsp;"); /*fix ie bug*/
    var select = $("<select>");
	if(typeof(selectClass) != "undefined"){
		select.addClass(selectClass);
	}
    var json = jsonData;
 
        for (var key in json) {
            if (!json.hasOwnProperty(key)) {
                continue;
            }
            var option = $("<option />").val(key).append( json[key] );  
			if(textValue == json[key] ) {$(option).attr('selected','selected')}      
            select.append( option ); 
        }
    labelHtml.append(select);
}

/***
 * 输入框默认显示文字，获取焦点后清除默认提示文字
 * @param {Object} element : 要操作的元素
 * @param {Object} defaultValue： 默认要显示的文字
 */
function klg_InputTips(element,defaultValue){
	var _default = defaultValue.toString();
	$element = $(element);
	$element.val(_default).addClass("gray_size12");
	$element.focus(function(){
		if ($(this).val()==_default){ 
			$(this).val("").removeClass("gray_size12");
		}
	})
	.blur(function(){
		if($(this).val() == ""){
			$(this).val(_default).addClass("gray_size12");
		}
	})
}//end klg_InputTips


/***
 * * set input default value
 * @param {jquery Object} $inputTag : jquery html tag,eg: $(".class")
 * @param {bool} isSelect:click will select textInput' text  ,default:true
 * @param {Object} defaultClass 
 * @param {Object} focusField
 */
function T_InputDefaultValue($inputTag,isSelect,defaultClass,focusField){
    
    //set default style
    isSelect = (typeof(isSelect) == "undefined") ? true : isSelect; 
    defaultClass = (typeof(defaultClass) == "undefined") ? "defaultValue" : defaultClass; 
    focusField = (typeof(focusField) == "undefined") ? "focusField" : focusField; 
    
    $inputTag.addClass(defaultClass);
    //have focus 获得焦点时触发
    $inputTag.focus(function(){
        $(this).removeClass(defaultClass).addClass(focusField);
        if (this.value == this.defaultValue) {
            this.value = '';
        }
        
        if (isSelect == true) {
            if (this.value != this.defaultValue) {
                this.select();
            }
        }
//        console.info(this.value);
//        console.info(this.defaultValue);
        
    })
    //失去焦点时触发
    .blur(function(){
        $(this).removeClass(focusField).addClass(defaultClass);
        if ($.trim(this.value) == '') {
            this.value = (this.defaultValue ? this.defaultValue : '');
        }
    });
    
}//end InputDefaultValue



/***
 * 全选，全不选
 * @param {Object} mode
 */
jQuery.fn.checkBox = function(mode){
    var mode = mode || 'on'; // if mode is undefined, use 'on' as default
    return this.each(function() {
		switch(mode) {
		case 'on':
			this.checked = true;
			break;
		case 'off':
			this.checked = false;
			break;
		case 'toggle':
			this.checked = !this.checked;
			break;
		}
	});
}

jQuery.fn.PagingNav = function(options){
    var defaults = {
        start : 0,
        pagesize: 20,//page size
        total: 20,//total asset
        pageno:1,//page No
        callFirst: function(){},
        callPrevious: function(){},
        callNext: function(){}
    }
    var settings = $.extend({}, defaults, options);
    
    var htmlString = '<div class="pagination-clean">' +
    '<a class="first" href="javascript:void(0)">&laquo;First</a>' +
    '<a class="previous" href="javascript:void(0)">&lsaquo;Prev</a>' +
    '<span class="active_page"><strong>'+ settings.start +'</strong> - <strong>'+ (settings.pagesize < settings.total ? (settings.pagesize)*settings.pageno : settings.total) +'</strong> of about <strong>'+localNumberFormatted(settings.total,false,'')+'</strong></span>' +
    '<a class="next" href="javascript:void(0)">Next &rsaquo;</a>' +
    '</div>';
//    console.info(settings.start,settings.pagesize,settings.total,settings.pageno)
    var $target = $(this);
    $target.append(htmlString);
    //init page default state
    //$(".previous", $target).hide();
    if(settings.total <= settings.pagesize){
        $(".previous,.next", $target).hide();
    }  
    
    var pageNo = settings.pageno;
    if (pageNo <= 1) {
        $(".previous", $target).hide();
		$(".first", $target).hide();
    }
    else if (pageNo == 2) {
        $(".first", $target).hide();
    }
    $(".next", $target).click(function(){
        $(".previous", $target).show();
        settings.callNext();
//        pageNo++;
//        if (pageNo == 2) {
//            $(".first", $target).hide();
//        }
//        console.info(pageNo);
    })
    $(".previous", $target).click(function(){
        settings.callPrevious();
//        pageNo--;
//        if (pageNo <= 1) {
//            $(".previous", $target).hide();
//        }
//        else if (pageNo == 2) {
//                $(".first", $target).hide();
//        }
//        console.info(pageNo);
    })
    
    $(".first", $target).click(function(){
        settings.callFirst();
//        pageNo = 1;
//        $(".previous", $target).hide();
    })
}//end PagingNav

/***
 * 按回车提交事件
 * @param {Object} subFun:回车调用函数
 */
jQuery.fn.OnCtrlEnter = function(subFun){
    $target = $(this);
    $target.keydown(function(event){
        var myEvent = event || window.event;
        var keyCode = myEvent.keyCode;
        if (myEvent.ctrlKey &&  keyCode == 13) {
            subFun();
        }
    });
}

//function LinkJump(url,time){
//	var _url = url;
//	var _time = (typeof(time) == "undefined") ? 0 : time; 
//	setTimeout(function(){
//		window.location.href = _url;
//	},_time);
//}

jQuery.fn.maxLengthPerReply = function( maxlimit,countfield ){
	$(this).bind('keyup keydown', function(){
		var status = $(this).val();       
		if   ( status.length  >   maxlimit)   {   
		  	$(this).val( status.substring(0,   maxlimit));   
		}  else {
			if( countfield ){				
				$(countfield).text( maxlimit   -   status.length ) ;
			}
		}		
	});	
}

function getIndexName(indexName) {
	var name = indexName;
	switch( name ){
		case '^GSPC' :
			name = 'S&P500';
			break;
		case '^DJI' :
			name = 'DOW';
			break;
		case '^IXIC' :
			name = 'NASDAQ';
			break;
		default:
			break;
	}
	return name;
}

/***
 * 发送Email类
 * sendEmail(sysmsg,txt)
 */
var KlgEmailNoticeClass = function(){
	var _getHostName = function(){
		var elggHost = location.protocol + "//" + location.host;
		if (elggHost == location.protocol + "//" + "localhost") {
			elggHost = elggHost + "/elgg";
		}
		return elggHost;
	}
	var seriveApi = _getHostName() + "/mod/feedback/actions/submit_feedback.php";
	var userInfo = {
		page: location.pathname,
		mood: "angry",
		about: "javascript_bug",
		id:"unknow email",
		errorMessage:"user feedback",
		userAgent: window.navigator.userAgent,
		userIp: function(){
			//判断是否存在，且是否是个function
			if(typeof GetUserIp != "undefined" && $.isFunction(GetUserIp)){
				return GetUserIp();
			}else{
				return "no ip";
			}
		},
		userTime: (new Date()).format("yyyy-MM-dd hh:mm:ss.S") //dateUtils.js
	};
	
	/***
	 * send js error email
	 * @param {Object} sysmsg:system error message
	 * @param {Object} txt:user message
	 */
	var _jsErrorFeedback = function(sysmsg,txt){
		
		userInfo["errorMessage"] = sysmsg;
		userInfo["txt"] = txt || "Please contact developer!";
//		if(_getHostName().indexOf("www.kalengo.com")){
//			alert(userInfo["txt"]);
//		}
		jQuery.ajax({
			url: seriveApi,
			type: "POST",
			data: userInfo,
			cache: false,
			dataType: "html"
		});
		
	};
	
	var _normalFeedback = function(options,success){
		var success = success || function(){};
		jQuery.extend(userInfo,options);
		jQuery.ajax({
			url: seriveApi,
			type: "POST",
			data: userInfo,
			cache: false,
			dataType: "html",
			success:success
		});
	}
	
	return{
		getHostName:_getHostName(),
		//发送email
		sendJsErrorEmail:function(sysmsg,txt){
			_jsErrorFeedback(sysmsg,txt);
		},
		sendFeedback:function(options,success){
			_normalFeedback(options,success);
		}
	}
	
}

/***
 * string 添加 格式化string方法
 * eg: alert("{0}-{1}".format("1","2"));
 */
String.prototype.formats = function()
{
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,               
        function(s,i){
            return args[i];
        });
}

/***
 * set cookies
 * @param {Object} name
 * @param {Object} value
 * @param {Object} days
 */ 
function klgSetCookie(name, value, days){
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else 
        var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

/***
 * get cookies 
 * @param {Object} name:cookies name
 */
function klgGetCookie(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 unescape( c.substring(nameEQ.length, c.length) );
    }
    return null;
}

/***
 * del cookies
 * @param {Object} name
 */
function klgDropCookie(name){
    klgSetCookie(name, "", -1);
}


/***
 * 封装window.open弹窗
 */
//PopUpAdClass = { };
PopUpAdClass = function(){
	// Private fields 
	var that = this;
	var windowHandles = {};
	var isChrome = /chrome/.test(navigator.userAgent.toLowerCase());
	
	// Public Members 
	this.focus = function(windowHandle){
		if (!windowHandle) {
			throw new Exception("Window handle can not be null.");
		}
		
		if (isChrome) {
			windowHandle.blur();
			setTimeout(windowHandle.focus, 0);
		}
		else {
			windowHandle.focus();
		}
	}
	
	this.windowExists = function(windowTarget){
		return windowTarget && windowHandles[windowTarget] && !windowHandles[windowTarget].closed;
	}
	
	this.open = function(url, windowTarget, windowProperties){
		// See if we have a window handle and if it's closed or not. 
		if (that.windowExists(windowTarget)) {
		
			// We still have our window object so let's check if the URLs is the same as the one we're trying to load. 
			var currentLocation = windowHandles[windowTarget].location;
			
			if ((/^http(?:s?):/.test(url) && currentLocation.href !== url) ||
			(			// This check is required because the URL might be the same, but absolute, 
			// e.g. /Default.aspx ... instead of http://localhost/Default.aspx ... 
			!/^http(?:s?):/.test(url) &&
			(currentLocation.pathname + currentLocation.search + currentLocation.hash) !== url)) {
				// Not the same URL, so load the new one. 
				windowHandles[windowTarget].location = url;
			}
			
			// Give focus to the window. This works in IE 6/7/8, FireFox, Safari but not Chrome. 
			// Well in Chrome it works the first time, but subsequent focus attempts fail,. I believe this is a security feature in Chrome to avoid annoying popups. 
			that.focus(windowHandles[windowTarget]);
		}
		else {
			// Need to do this so that tabbed browsers (pretty much all browsers except IE6) actually open a new window 
			// as opposed to a tab. By specifying at least one window property, we're guaranteed to have a new window created instead 
			// of a tab. 
			//windowProperties = windowProperties || 'menubar=yes,location=yes,width=700, height=400, scrollbars=yes, resizable= yes'; 
			windowProperties = windowProperties || 'menubar=yes,location=yes,width=' + (screen.availWidth - 15) + ', height=' + (screen.availHeight - 140) + ', scrollbars=yes, resizable= yes';
			windowTarget = windowTarget || "_blank";
			
			// Create a new window. 
			var windowHandle = windowProperties ? window.open(url, windowTarget, windowProperties) : window.open(url, windowTarget);
			
			if (null === windowHandle || !windowHandle) {
				alert("You have a popup blocker enabled. Please allow popups for " + location.protocol + "//" + location.host);
			}
			else {
				if ("_blank" !== windowTarget) {
					// Store the window handle for reuse if a handle was specified. 
					windowHandles[windowTarget] = windowHandle;
					windowHandles[windowTarget].focus();
				}
			}
		}
	}
}



/***
 * JS debug for website
 */
var WebSiteConfig = window.WebSiteConfig || {};
WebSiteConfig.DEBUG = (location.hostname.indexOf('localhost') !== -1);
//WebSiteConfig.DEBUG = false;
//初始化debug为空对象
klgDebug = {}
klgDebug.log = function(msg){
	return false;
};
klgDebug.info = function(msg){
	return false;
};
//alert(typeof(console));
if(WebSiteConfig.DEBUG && typeof(console) !== "undefined"){
	klgDebug = console;
}
//eg: klgDebug.log("klgDebug");





////////////////////////////////////////check user login or not before click event////////////////////
//增加点击link的响应
function checkSigninFunctionOnClick(jqueryString)
{
	$(jqueryString).click(function(){
		if(loginUserId < 0 ) {		
			if( !klgGetCookie("latest_email") )
			{	
				window.location.href = elggHttpsHost + 'account/register.php';
				
			}else{
				window.location.href = elggHttpsHost + 'account/login.php';
			}
		}
		return false;
		
	})
}










