/** W3Softwares Javascript Library -- Based on jQuery library
*	All rights reserved
*	@copyright	w3softwares.com
***/
var W3S = {};
W3S.sequence = W3S.sequence || 1;  // shared sequence for generic use
W3S.prefixId = 'W3S_';	// for generated DOM's id
W3S.defaultLang = $('html').attr('lang')?$('html').attr('lang').toLowerCase():'en';
W3S.component = {};
W3S.data = W3S.data||{};
W3S.data = {
	popup: W3S.data.popup||new Array()
};
W3S.util = {};
W3S.util.misc = {
	print: function(msgTag, msg, replace) {
		var pos = msgTag?$('#'+msgTag):null;
		if (replace) {
			for (var key in replace) {
				msg = msg.replace(key, replace[key]);
			}
		}
		if (msgTag && pos.length) {
        	pos.html(msg);
		} else {
			alert(msg);
		}
	},
	clock: function(utc){
		var currentTime = new Date();
		var title = W3S.language.messages[W3S.defaultLang][utc=='1'?'utcTime':'localTime'];
		if (utc=='1') {
			var temp = currentTime.toGMTString();
			currentTime = new Date(temp.substring(0, temp.lastIndexOf(" ")));
		}
		var currentFullYear = currentTime.getFullYear();
		var currentMonth = currentTime.getMonth()+1;
		var currentDate = currentTime.getDate();
		var currentHours = currentTime.getHours();
		var currentMinutes = currentTime.getMinutes();
		var currentSeconds = currentTime.getSeconds();

		// Pad the minutes and seconds with leading zeros, if required
		currentMonth = ( currentMonth < 10 ? "0" : "" ) + currentMonth;
		currentDate = ( currentDate < 10 ? "0" : "" ) + currentDate;
		currentHours = ( currentHours < 10 ? "0" : "" ) + currentHours;
		currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
		currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

		// Compose the string for display
		var currentTimeString = title+" "+currentFullYear+"-"+currentMonth+"-"+currentDate+" "+currentHours+":"+currentMinutes+":"+currentSeconds+" ";
		$('#clock').html(currentTimeString);
	},
	getTimezone: function() { // thanks Josh Fraser sharing on http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/
		var rightNow = new Date();
		var temp = rightNow.toGMTString();
		var gmTime = new Date(temp.substring(0, temp.lastIndexOf(" ")));
		var offset = (rightNow - gmTime) / (1000 * 60 * 60);
		return offset>0?Math.ceil(offset):Math.floor(offset);
	},
	setCookie: function(name, val, expiredays) {
		var exdate=new Date();
		exdate.setDate(exdate.getDate()+expiredays);
		document.cookie=name+"="+escape(val)+";path=/"+((expiredays==null)?"":";expires="+exdate.toUTCString());
	},
	response: function(res, message, option) {
		if (!res) return false;
		if (option.callback && (option.dataType=='html'||res.success)) {
			if (typeof option.callback !== 'function') {
				window['member_list'](res);
			} else {
				option.callback(res);
			}
			return false;
		}
        if (option.dataType=='html') {
            if (res=='OK'||res=='ok') {
                W3S.util.misc.print(option.msgTag,message['ok']);
                window.location.reload();
            } else if (res=='ERR'||res=='failure') {
                W3S.util.misc.print(option.msgTag, message['failure']);
            } else {
                W3S.util.misc.print(option.msgTag, res);
				if (option.reload) {
                	window.location.reload();
				}
            }
        } else if (res.success) {
            var mesg = res.message?(message[res.message]?message[res.message]:res.message):message['ok'];
            if (res.message && mesg) {
                W3S.util.misc.print(option.msgTag, mesg, res.replace);
            }
            if (res.reload!='none') {
				if (option.refreshDom) {
					var $target = $('#'+option.refreshDom);
                    $.ajax({
                        url: $target.attr('rel'),
                        success: function(html){
                            $target.replaceWith(html);
                        }
                    });
				} else if (res.redirect) {
					window.location.href = res.redirect;
				} else {
                	window.location.reload();
				}
            }
        } else if (res.message=='0') {
            // do nothing
        } else if (res.message) {
            W3S.util.misc.print(option.msgTag, message[res.message]?message[res.message]:res.message);
        } else {
            W3S.util.misc.print(option.msgTag, message['failure']);
        }
	},
	popupRefresh: function(){
		if (W3S.data.popup.length<1) {
			return;
		}
		var popup = W3S.data.popup[W3S.data.popup.length-1];
		W3S.util.ajax.popupLoad(popup.id, popup.url);
	},
	popupResize: function(popupId){
		var $popupObj = $('#'+popupId);
        var $offset = $popupObj.hasClass('nobutton')?50:106;
        var $popBody = $('#'+popupId).children().first();
		if ($popBody.width()<10) {
			$popBody = $popBody.children().first();
		}
        var $width = Math.max(200,$('#'+popupId).width(),$popBody.width(),$('#'+popupId+' table').width());
        var $height = Math.max(30,Math.min(Math.max($('#'+popupId).height(),$popBody.height())+$offset, $(window).height()));
        var $left = ($(window).width()-$width)/2;
        var $top = ($(window).height()-$height)/2;
        if ($width<1) {
            return false;
        }
        $popupObj.dialog("option","width", $width+40);
        $popupObj.dialog("option","position",[$left, $top]);
        if ($height==$(window).height()) {
            $popupObj.css('height', $height-$offset);
        }
		return null;
	},
	changeVerificationImage: function(imgId) {
		$img = $('#'+imgId);
		$img.attr('src', $img.attr('src').replace(/s\d+$/g, 's'+Math.floor(Math.random()*1000)));
	}
};
W3S.util.event = {
	tab: function() {
		var $url = $(this).attr('href');
		var $target = $(this).attr('target');
		$('#'+$target).removeClass('hidden').siblings().addClass('hidden');
        $(this).parent().addClass('selected').siblings().removeClass('selected');
		if ($url.substring(0, 1)!='#') {
			$target.load($url);
		}
		return false;
	},
	cell: function() {
		$(this).removeClass('cell dirty');
		var val = $(this).val
		$(this).blur(function(){$(this).addClass('cell');}).change(function(){$(this).addClass('dirty');});
		return false;
	},
	popUp: function() {
		var obj = new W3S.component.popUp();
		obj.bind($(this));
		return false;
	},
	dialog: function() {
        var $promption = $(this).attr('rel');
        if ($promption.length>1) {
            if (!confirm($promption)) {
                return false;
            }
        }
        //alert($(this).attr('id'));
		var url = $(this).attr('href')?$(this).attr('href'):window.location.href;
		var ajax = false;
        var popupId = "w3s-dialog-"+W3S.sequence++;
		if (url.substr(0,1)!='#') {
			ajax = true;
        	$('body').append('<div id="'+popupId+'" style="padding:0 auto;"></div>');
		} else {
        	$('body').append('<div id="'+popupId+'" style="padding:0 auto;">'+$(url).html()+'</div>');
		}
        var $popupObj = $('#'+popupId);
		var btn_close = W3S.language.messages[W3S.defaultLang]['close'];
		var btn_submit = W3S.language.messages[W3S.defaultLang]['submit'];
		var btn_reset = W3S.language.messages[W3S.defaultLang]['reset'];
		var buttons = {}; 
        if ($(this).hasClass('nobutton')) {
			$popupObj.addClass('nobutton');
        } else if ($(this).hasClass('nosubmit')||!ajax) {
			buttons[btn_close] = function(){$(this).dialog('close');};
        } else {
			buttons[btn_close] = function(){$(this).dialog('close');};
			buttons[btn_submit] = function(){$('#'+popupId+' form').first().submit();};
			buttons[btn_reset] = function(){$('#'+popupId+' form')[0].reset();};
        }
		var refresh = $(this).hasClass('child');
		var closeFn = function(){
                $popupObj.remove();
				W3S.data.popup.pop();
				if (refresh) {
                    W3S.util.misc.popupRefresh();
                }
            };
        var options = {
            modal:$(this).hasClass('nomodal')||$(this).hasClass('child')?false:true,
            title:$(this).attr('title').length?$(this).attr('title'):$(this).text(),
            close:closeFn,
			buttons: buttons
        };
		W3S.data.popup.push({'id':popupId,'url':url});
        $popupObj.dialog(options);
		if (ajax) {
			W3S.util.ajax.popupLoad(popupId, url);
		} else {
			W3S.util.misc.popupResize(popupId);
		}
    	return false;
	},
	action:function() {
		/// title for confirmation
        if ($(this).attr('title').length<1 || confirm($(this).attr('title'))) {
            var $target = $(this).attr('target')?$('#'+$(this).attr('target')):null;
            if ($target) {
				if ($(this).hasClass('trigger')) {
					// trigger event 'href' which bind on other object('target')
					$target.trigger($(this).attr('name'));
				} else if ($(this).hasClass('submit')) {
					$target.submit();
				} else if ($(this).hasClass('reset')) {
					$target[0].reset();
				} else if ($(this).hasClass('more')) {
					$target.html('<img src="/resources/w3s/ux/img/ajax-loader.gif" />');
					$.ajax({
						url:$(this).attr('href'),
						success: function(html){
                			$target.replaceWith(html);
			            }
			        });
				} else if ($(this).hasClass('verification')) {
					// change verification image
					W3S.util.misc.changeVerificationImage($(this).attr('target'));
				} else {
                	// ajax load to specific dom (by target)
	                $target.load($(this).attr('href'), {'data':$(this).attr('rel')}, $(this).attr('name'));
				}
            } else {
                W3S.util.ajax.post($(this).attr('href'), $(this).attr('rel'), {'callback':$(this).attr('name')});
            }
        }
        return false;
	},
	disable:function(){return false;}
};
W3S.util.ajax = {
	fieldValidation: function(options) {
        var invalidFields = [];
        $('#'+options.formId+' .mandatory').each(function() {
            $(this).removeClass(options.errCls);
            if (!$(this).val().match(/[^\s]+/)) {
				invalidFields.push($(this).attr('name'));
                $(this).addClass(options.errCls);
            }
        });
		$('#'+options.formId+' .alphaNum').each(function() {
            $(this).removeClass(options.errCls);
            if (!$(this).val().match(/^s*\w+\s*$/i)) {
				invalidFields.push($(this).attr('name'));
                $(this).addClass(options.errCls);
			}
		});
		$('#'+options.formId+' .email').each(function() {
            $(this).removeClass(options.errCls);
            if (!$(this).val().match(/^[^@]+@[^@\.]+\.[^@]+$/i)) {
				invalidFields.push($(this).attr('name'));
                $(this).addClass(options.errCls);
			}
		});
		return invalidFields;
	},
	popupLoad:function(popupId, url) {
		var $popupObj = $('#'+popupId);
        $popupObj.html(W3S.language.messages[W3S.defaultLang]['loading']);
        $popupObj.load(url, function(){
            $('#'+popupId+' form .button_line').remove();
			W3S.util.misc.popupResize(popupId);
        });
	},
	post: function(url, param, options, messages) {
		var option = {
			'dataType':'json',
			'callback':null
		};
		var message = W3S.language.messages[W3S.defaultLang];
		if (options) $.extend(option, options);
		if (messages) $.extend(message, messages);
		$.post(url, param, function(res){
			W3S.util.misc.response(res, message, option);
		},option.dataType);
		return false;
	},
	form: function(formId, options, messages) {
		// depends on jQuery ajaxForm plugin
		// optional: msgTag, dictionary of res.message
		var option = {
            'dataType':'json',
            'msgTag':null, // using alert box
            'errCls':'errField',
	        'modalDom':'modal_page',
			'refreshDom':null,
            'callback':null
		};
		var message = W3S.language.messages[W3S.defaultLang];
		if (options) $.extend(option, options);
		if (messages) $.extend(message, messages);
		if (option.refreshDom) option.dataType='html';
		var modal_page = option.modalDom;
        var config = {
            dataType: option.dataType,
            beforeSubmit: function() {
				$('body').append('<div id="'+modal_page+'"></div>');
				// 100% height doesn't work in some cases
				if (option.refreshDom&&W3S.data.popup.length==0) {
					var refDom = $('#'+option.refreshDom);
					var refPos = refDom.position();
					$('#'+modal_page).height(refDom.height()).width(refDom.outerWidth()).
					css({'position':'absolute','left':refPos.left,'top':refPos.top});
				} else {
					$('#'+modal_page).height(Math.max($('body').height(),$(window).height()));
				}
                var formOptions = {
					'formId':formId,
					'color':'transparent', 
					'errCls':option.errCls
				};
                var invalidFields = W3S.util.ajax.fieldValidation(formOptions);
                if (invalidFields.length) {
					$('#'+modal_page).remove();
					W3S.util.misc.print(option.msgTag, message['invalidValue']);
                    return false;
                }
                return true;
            },
            success: function(res) {
				$('#'+modal_page).remove();
				if (option.dataType=='html'&&(res=='ok'||res=='OK'||res=='ERR'||res=='failure')) {
					W3S.util.misc.response(res, message, option);
				} else if (option.refreshDom) {
					$('#'+option.refreshDom).replaceWith(res);
				} else {
					W3S.util.misc.response(res, message, option);
				}
            }
        };
        $('#'+formId).ajaxForm(config);
	}
};

W3S.component.popUp = function(options)
{
	// default config
	var config = {
 		'title':null,
		'type':'center',
 		'modal': true
	};
	if (options) $.extend(config, options);
	// tag Id initialization
	var popupId = W3S.prefixId+'ui_popup';
	var containerId = popupId+'_container';
	var titleId = popupId+'_title';
	var closerId = popupId+'_closer';
	var bodyId = popupId+'_body';
	var buttonId = popupId+'_button';

	var $popup = null;
	

	var renderPopup = function() {
		$('#'+bodyId).removeClass('loading');
		if ($popup) {
			if ($('#'+bodyId+' form .button_line').length) {
				var close_btn = '<a class="button action trigger" href="#" name="click" target="'+closerId+'">'+W3S.language.messages[W3S.defaultLang]['close']+'</a>';
				$('#'+buttonId).html($('#'+bodyId+' form .button_line').html()+'&nbsp;'+close_btn);
				$('#'+bodyId+' form .button_line').remove();
			} else {
				$('#'+buttonId).remove();
			}
			centerPopup();
		}
	}
 
	//disabling popup with jQuery magic!
	var closePopup = function() {
		if ($popup)	$popup.fadeOut("slow", function() {
			W3S.data.popup.pop();
			$(this).remove();
			$popup = null;
			popupStatus=0;
		});
	}
 
	//centering popup
	var centerPopup = function() {
		//request data for centering
 		popupStatus = 1;
		var windowHeight = $(window).height();
		var popupHeight = $('#'+bodyId).height();
		//centering
		var $container = $('#'+containerId);
		$container.css({
			'top': Math.max(0, windowHeight/2-popupHeight/2-80)
		});
		if ($container.height()>$(window).height()) {
			$container.height($(window).height()*.85);
		}
		if ($container.width()>$(window).width()) {
			$container.width($(window).width()*.85);
		}
	};
	// public method
	this.bind = function($obj) {
		var title = $obj.attr('title')||$obj.text();
		var modal = $obj.hasClass('modal') || config.modal;
		if (!modal) {
			popupId += W3S.sequence++;
			containerId = popupId+'_container';
			titleId = popupId+'_title';
			closerId = popupId+'_closer';
			bodyId = popupId+'_body';
			buttonId = popupId+'_button';
		}
		var popup_html;
		if (config.type=='dropdown') {
			popup_html = '<div id="'+bodyId+'" class="body loading"></div><div id="'+buttonId+'" class="button-line"></div><div id="'+closerId+'" class="closer right">&nbsp;&nbsp;</div>';
		} else {
			popup_html = '<div id="'+titleId+'" class="title"><div id="'+closerId+'" class="closer">&nbsp;&nbsp;</div><h1>'+title+'</h1></div>\n'+
			            '<div id="'+bodyId+'" class="body loading"></div><div id="'+buttonId+'" class="button-line"></div>';
		}
		popup_html = '<div id="'+popupId+'" class="w3s-popup"><table cellspacing="0" cellpadding="0"><tr><td><div id="'+containerId+'" class="container">'+popup_html+'</div></td></tr></table></div>';
 		closePopup();
 		$('body').append(popup_html);
 		$popup = $('#'+popupId);

 		if (modal) {
 			$popup.addClass('modal');
 		}
		if (title) {
			$('#'+titleId+' h1').html(title);
		}
		$popup.fadeIn("slow");
 		//2. loading content into popup and ajust popup position
		W3S.data.popup.push({'id':popupId,'url':$obj.attr('href')});
 		$('#'+bodyId).load($obj.attr('href'), null, renderPopup);
		//Press Escape event!
		$(document).keypress(function(e){
			if(e.keyCode==27 && popupStatus==1){
				closePopup();
			}
		});
		$('#'+closerId).click(function(){
			closePopup();
			return false;
		});
		return false;
	}
};

W3S.language = {
	'messages': {
		'zh-cn': {
			'invalidValue':'对不起，红色背景项缺少数据或不符合要求，请按要求填写后再提交。',
			'mandatory':'对不起，红色背景项是必要数据。请输入完整数据后再提交。',
			'ok':'谢谢，您的提交已处理完毕。',
			'loginFailure':'对不起，你提交的用户名和密码不对，\n请使用有效的用户名和密码再试。',
			'verifyFailure':'校验码不对，请重新输入再试。',
			'failure':'很抱歉，提交处理出错，请稍后再试或与我们联系。',
			'confirm':'确认密码与密码不符，请重新输入再试。',
			'oldPwd':'很抱歉，旧密码不对，请重新输入再试。',
			'duplicated':'很抱歉，该用户名已被他人注册，请选用其他用户名再试。',
			'newPwd':'处理完毕！用户::USER::的密码已经更新为::NEWPWD::。',
			'newPwdOk':'谢谢！您的密码已更新。',
			'noChanged':'没有更新数据提交，数据没有发生变化。',
			'reset':'复位',
			'close':'关闭',
			'submit':'提交',
			'loading':'正在导入......',
			'localTime':'本地时间',
			'utcTime':'格林威治时间'
		},
		'en': {
			'invalidValue':'Sorry, red background fields are invalid. Please check it and try again.',
			'mandatory':'Sorry, no data found in a mandatory field.',
			'ok':'Thank you! Your submit has been processed.',
			'loginFailure':'Sorry, Invalid ID or password. \nPlease check your user Id and password and try again.',
			'verifyFailure':'Verification code is wrong, please try again',
			'failure':'Sorry, failed to process your submit. Please try it later.',
			'confirm':'Sorry, confirm password and password do not match.',
			'oldPwd':'Sorry, the old password is wrong, please try again.',
			'duplicated':'Sorry, the User Id is not available, please use another and try again.',
			'newPwd':'OK, new password for user ::USER:: is ::NEWPWD::.',
			'newPwdOk':'OK, your password has been updated.',
			'noChanged':'No modified data submitted, nothing has been changed.',
			'reset':'Reset',
			'close':'Close',
			'submit':'Submit',
			'loading':'Loading ...',
			'localTime':'Local Time',
			'utcTime':'UTC'
		}
	}
};
$(document).ready(function(){
	W3S.util.misc.setCookie('localTimezone', W3S.util.misc.getTimezone());
	$('a.disabled').live('click', W3S.util.event.disable);
	$('a.popup').live('click', jQuery.ui?W3S.util.event.dialog:W3S.util.event.popUp);
    $('a.action').live('click', W3S.util.event.action);
	$('a.tab').live('click', W3S.util.event.tab);
	$('input.cell').live('click', W3S.util.event.cell);
	if ($('#clock')) {
		var utc = $('#clock').hasClass('utc')?'1':'0';
		W3S.util.misc.clock(utc);
		setInterval("W3S.util.misc.clock('"+utc+"')", 1000);
	}
});

