/*
 * @package     Kepingin.Framework - Global Scripts
 * @author      Tu Masdan E.P. <utu.eka@gmail.com>
 * @copyright   2008 Babon Multimedia
 * @website		http://www.babonmultimedia.com
 * @version     1.0.1
 * @changed		11/05/2008 3:48 AM
 * @license     -
 * @link        -
*/


/*------------------------------------------------------------------------------
Global Scripts
------------------------------------------------------------------------------*/

;(function($){
	$.extend($.ajaxSettings.accepts, {css: 'text/css'});
	
	$.emptyFn = function(){ 
		void(0); 
	};	
	
	$.getDom = function(el){
		if(!el){
			return null;
		}
		
		return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
	};
	
	$.callback = function(cb, scope, args, delay){
		if(typeof cb == "function"){
			if(delay){
				cb.defer(delay, scope, args || []);
			}else{
				cb.apply(scope, args || []);
			}
		}
	};
	
	$.urlEncode = function(o){
		if(!o){
			return "";
		}
		var buf = [];
		for(var key in o){
			var ov = o[key], k = encodeURIComponent(key);
			var type = typeof ov;
			if(type == 'undefined'){
				buf.push(k, "=&");
			}else if(type != "function" && type != "object"){
				buf.push(k, "=", encodeURIComponent(ov), "&");
			}else if(ov instanceof Array){
				if (ov.length) {
					for(var i = 0, len = ov.length; i < len; i++) {
						buf.push(k, "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
					}
				} else {
					buf.push(k, "=&");
				}
			}
		}
		buf.pop();
		return buf.join("");
	};
	
	$.urlDecode = function(string, overwrite){
		if(!string || !string.length){
			return {};
		}
		var obj = {};
		var pairs = string.split('&');
		var pair, name, value;
		for(var i = 0, len = pairs.length; i < len; i++){
			pair = pairs[i].split('=');
			name = decodeURIComponent(pair[0]);
			value = decodeURIComponent(pair[1]);
			if(overwrite !== true){
				if(typeof obj[name] == "undefined"){
					obj[name] = value;
				}else if(typeof obj[name] == "string"){
					obj[name] = [obj[name]];
					obj[name].push(value);
				}else{
					obj[name].push(value);
				}
			}else{
				obj[name] = value;
			}
		}
		return obj;
	};
	
	$.setTimezone = function(){
		var date = new Date();
		var timezone = "timezone=" + -date.getTimezoneOffset() * 60;
		date.setTime( date.getTime() + (1000*24*60*60*1000) );
		
		var expires = "; expires=" + date.toGMTString();
		document.cookie = timezone + expires + "; path=/; domain=." + location.host
	};
	
	$.getPageSize = function(){
		var de = document.documentElement;
		var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
		var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
		
		arrayPageSize = new Array(w,h);
		return arrayPageSize
	};
		
	$.hide_selectboxs = function(){
		for(var i = 0; i < document.forms.length; i++) {
			for(var e = 0; e < document.forms[i].length; e++){
				if(document.forms[i].elements[e].tagName == 'SELECT') {
					document.forms[i].elements[e].style.visibility='hidden';
				}
			}
		}
	};
	
	$.show_selectboxs = function(){
		for(var i = 0; i < document.forms.length; i++) {
			for(var e = 0; e < document.forms[i].length; e++){
				if(document.forms[i].elements[e].tagName == 'SELECT') {
					document.forms[i].elements[e].style.visibility='visible';
				}
			}
		}
	};
	
	$.disable_form = function( el ){
		var form = $.getDom( el );
		if( !form ) return false;
		
		var elements = form.elements;
		if( !elements.length  ) return false;
		
		for( var i=0; i<elements.length; i++ ){
			var element = elements[i];
			var type = String(element.type).toLowerCase();
			
			if( type=='undefined' ) continue;
			if( type=='hidden' ) continue;
			
			element.disabled = 'true'
		}
		
		return true
	};
	
	$.enable_form = function( el ){
		var form = $.getDom( el );
		if( !form ) return false;
		
		var elements = form.elements;
		if( !elements.length  ) return false;
		
		for( var i=0; i<elements.length; i++ ){
			var element = elements[i];
			var type = String(element.type).toLowerCase();
			
			if( type=='undefined' ) continue;
			if( type=='hidden' ) continue;
			
			element.disabled = ''
		}
		
		return true
	};
	
	$.waitCursor = function(){document.body.style.cursor = 'wait'};
	
	$.defaultCursor = function(){document.body.style.cursor = 'default'};
	
	$.jserror = function( text, callback ) {
		$.showMsg( '<h2 class="jtitle-error">Error...</h2><p class="jtext-error">' + text + '</p>',
				callback
			)
	};
	
	$.jswarn = function( text, callback, ul ) {
		$.showMsg( '<h2 class="jtitle-warn">Warning...</h2><p class="jtext-warn">' + text + '</p>',
				callback
			)
	};
	
	$.jsinfo = function( text, callback ) {
		$.showMsg( '<h2 class="jtitle-info">Info...</h2><p class="jtext-info">' + text + '</p>',
				callback
			)
	};
	
	$.showMsg = $showMessage = function( message, callback ){
		if( $.isFunction(callback) ) callback = {onhide: callback};
		
		$.facebox(message, 
				null, 
				$.extend({onshow: null, onhide: null}, callback)
			);
		
		setTimeout(function(){
				$.closeMsg()
			}, 50000)
	};
	
	$.closeMsg = $.closeMessage = function(){
		$.facebox.close()
	};
	
	$.fixPng = function( png ) {
		// replace by blank image
		if( document.transparent_img == undefined ){
			document.transparent_img = new Image();
			document.transparent_img.onload = function(){
					$.fixPng( png )
				};
				
			document.transparent_img.src = '/resources/images/s.gif';
			return false;
		}
		
		// get src
		var src = png.src;
		
		// set width and height
		if ( !png.style.width ) { png.style.width = $(png).width(); }
		if ( !png.style.height ) { png.style.height = $(png).height(); }
		
		png.onload = function(){
				this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')"
			};
		png.src = document.transparent_img.src;
		
		// set filter (display original image)
		// png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
	};
	
	$.preloadCssImages = function(){
		var allImgs = [];//new array for all the image urls  
		var k = 0; //iterator for adding images
		var sheets = document.styleSheets;//array of stylesheets
		
		for(var i = 0; i<sheets .length; i++){//loop through each stylesheet
				var cssPile = '';//create large string of all css rules in sheet
				var csshref = (sheets[i].href) ? sheets[i].href : 'window.location.href';
				var baseURLarr = csshref.split('/');//split href at / to make array
				baseURLarr.pop();//remove file path from baseURL array
				var baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
				if(baseURL!="") baseURL+='/'; //tack on a / if needed
				if(document.styleSheets[i].cssRules){//w3
						var thisSheetRules = document.styleSheets[i].cssRules; //w3
						for(var j = 0; j<thisSheetRules.length; j++){
								cssPile+= thisSheetRules[j].cssText;
						}
				}
				else {
						cssPile+= document.styleSheets[i].cssText;
				}
				
				//parse cssPile for image urls and load them into the DOM
				var imgUrls = cssPile.match(/[^\(]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename"
				if(imgUrls != null && imgUrls.length>0 && imgUrls != ''){//loop array
						var arr = jQuery.makeArray(imgUrls);//create array from regex obj        
						jQuery(arr).each(function(){
								allImgs[k] = new Image(); //new img obj
								allImgs[k].src = (this[0] == '/' || this.match('http://')) ? this : baseURL + this;     //set src either absolute or rel to css dir
								k++;
						});
				}
		}//loop
		
		return allImgs;
	};
	
	$.getCss = function( href, media ){
		$.addStyleSheet( href, media )
	};
	
	$.addStyleSheet = function( url, media ){
		var $url = url || '';
		var $media = media || 'all';
		
		if( $url=='' ) return false;
		
		var $link = '<link rel="stylesheet" href="' + $url + '" type="text/css" media="'+ $media +'" />';
		$( 'head' ).append( $link )
	};
	
	$.addIcon = function( url ){
		var $url = url || '';
		
		if( $url=='' ) return false;
		
		var $link = '<link rel="shortcut icon" href="' + $url + '" />';
		if( !$.browser.msie ){
			$( 'head' ).append( $link );
		}
	};
	
	$.addScript = function( url, type, callback ){
		var $url = url || '';
		var $type = type || 'text/javascript';
		
		if( $url=='' ) return false;
		
		var $script = '<script type="' + $type + '" src="' + $url + '" onerror="alert(\'Error loading \' + this.src)"></script>';
		$( 'head' ).append( $script )
	};
	
	$.mask = null;
	$.fn.mask = function( status, callback ){
		if( $.mask == null ){
			var overlay = '<div id="mask-overlay" class="jmask">&nbsp;</div>'
				+ '<div id="mask-loader" class="jmask-outerloader">'
					+ '<div class="jmask-innerloader" style="width:100px;height:120px;left:-50px;top:-60px;text-align:center">'
						+ '<img src="/resources/images/indicator-mid.gif" />'
						+ '<small id="mask-status">sending</small>'
					+ '</div>'
				+ '</div>';
			
			$('body').append( overlay );
			
			$.mask = {};
			$.mask.overlay = $( 'div#mask-overlay' )[0];
			$.mask.loader = $( 'div#mask-loader' )[0];
			$.mask.status = $( 'small#mask-status' )[0];
		}
		
		if( $.browser.msie ) $( 'select', $( this ) ).hide();
		
		$( $.mask.overlay, $('body') )
			.appendTo( $( this ) )
			.show()
			// .width( $( this ).width() )
			.height( $( this ).height() );
		
		$( $.mask.loader, $('body') )
			.appendTo( $( this ) ).show();
		
		$( $.mask.status ).html( status || 'loading...' );
		$.waitCursor();
		
		if( typeof callback == 'function' ) callback.call( this )
	};
	
	$.fn.unmask = function( callback ){
		$( $.mask.status ).html( '' );
		
		$( $.mask.loader, $( this ) )			
			.hide()
			.appendTo( $('body') );
		
		$( $.mask.overlay, $( this ) )			
			.fadeOut('slow', function(){
					$( this ).appendTo( $('body') )
				});
		
		if( $.browser.msie ) $( 'select', $( this ) ).show();
		$.defaultCursor()
		
		if( typeof callback == 'function' ) callback.call( this )
	};
		
	$.fn.bindForm = function( values, attr ){
		if( values == {} ) return;
		
		$( 'input, textarea, select', this ).each(function(){
				var key = $( this ).attr( attr || 'name' );
				switch( this.type.toLowerCase() ){
					case 'text':
					case 'textarea':
					case 'hidden':
						$( this ).val( values[this.name] || '' );
					break;
					
					case 'select-one':
						$( 'option', this ).attr( 'selected', '' );
						$( 'option', this ).each(function(i){
								if( this.value == values[key] ) $( this ).attr( 'selected', 'true' )
							});
					break;
					
					case 'select-multiple':
						$( 'option', this ).attr( 'selected', '' );
						$( 'option', this ).each(function(i){
								if( $.inArray( this.value, values[key] ) ) $( this ).attr( 'selected', 'true' )
							});
					break;			
					
					case 'checkbox':
					case 'radio':
						$( this ).attr( 'checked', '' );
						if( typeof values[key] == 'object' ){
							if( $.inArray( this.value, values[key] ) ) $( this ).attr( 'checked', 'true' );
						} else {
							if( this.value == values[key] ) $( this ).attr( 'checked', 'true' );
						}
					break;
				}				
			})
	};
	
	$.fn.serializeForm = function(){
	};
	
	$.gotoTop = function( time, callback, scope ){
		if( typeof time == 'function' ){
			scope = callback;
			callback = time;
			time = 'slow';
		}
		
		$( 'html' ).animate({scrollTop:0}, time, function(){
				if( typeof callback == 'function' ){
					setTimeout(function(){
							callback.call( scope || $ )
						}, 100);
				}
			});
	};
	
	$.isEmail = function( value ){
		return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test( value )
	};
	
	$.isURL = function(){
		return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})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ber = function( value ){
		return /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test( value )
	}
})(jQuery);

/* -------------------------------------------- */
/* -- Site Bookmark --------------------------- */
/* -------------------------------------------- */
bookmarkSite = function( title, url ){
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all)// ie
		window.external.AddFavorite(url, title);
};

/* -------------------------------------------- */
/* -- Text Counter ---------------------------- */
/* -------------------------------------------- */
textCounter = function (fieldId, fieldCountId, maxLimit) {
	var fs = document.getElementById( fieldId );
	var fc = document.getElementById (fieldCountId );
	
	if (fs.value.length > maxLimit) {
		fs.value = fs.value.substring(0, maxLimit);
	} else {
		fc.value = maxLimit - fs.value.length;
	}
};

/* -------------------------------------------- */
/* -- Auto Resize Frame ----------------------- */
/* -------------------------------------------- */
autoResize = function( frameId ){
	try{
		var frame = document.getElementById( frameId );
		var inner = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
		
		if( browser.msie ){
			if( document.all ) frame.style.height = inner.body.scrollHeight + 20 + 'px';
		} else {
			frame.style.height = inner.body.scrollHeight + 20 + 'px';
		}
	}catch( err ){
		window.status = err.message;
	}
};

/* -------------------------------------------- */
/* -- Popup Window ---------------------------- */
/* -------------------------------------------- */
var JWinPopup = null;
openJPopup = function( url ){
	var ph = Math.floor( screen.height );
	var pw = Math.floor( screen.width );
	
	var settings = "toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no,width="+ pw +",height="+ ph +",left=0,top=0,screenX=0,screenY=0";
	
	if( JWinPopup ) JWinPopup.close();
	
	JWinPopup = open( url, "JWinPopup", settings );
	JWinPopup.focus();
};

if( typeof $.format == undefined ){
	$.format = function(source, params) {
		if ( arguments.length == 1 ) 
			return function() {
				var args = $.makeArray(arguments);
				args.unshift(source);
				return $.format.apply( this, args );
			};
		
		if ( arguments.length > 2 && params.constructor != Array  ) {
			params = $.makeArray(arguments).slice(1);
		}
		
		if ( params.constructor != Array ) {
			params = [ params ];
		}
		
		$.each(params, function(i, n) {
			source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
		});
		
		return source;
	};
}
