
var sys = new function(){

var _self = this;

	// pregQuote
	this.pregQuote = function(str){
		var quote_chars = ["\\", ".", "+", "*", "?", "[", "^", "]", "$", "(", ")", "{", "}", "=", "!", "<", ">", "|", ":"];
    	var return_val = new String(str);

    	for(var i=0;i<quote_chars.length;i++){
        	eval("var pattern = /\\"+quote_chars[i]+"/gi");
        	return_val = return_val.replace(pattern, String.fromCharCode(92)+quote_chars[i]);
    	}
    return return_val;
	}

	this.loadJS = function(uri, callback){
	document.write("<script language='javascript' src='"+uri+"' type='text/javascript'></script>");
	}

	this.loadCSS = function(uri, callback){
		document.write('<link rel="stylesheet" type="text/css" href="'+uri+'" />');
	}

	this.setValue = function(_var,_value){

		if(!window[_var]){
			window[_var] = _value;
		} else {

			for(var p in _value){
				window[_var][p] = _value[p];
			}

		}
	}

	this.formToObject = function sys_formToObject($form){
		var data = {};
		$('input, select, textarea',$form).each(function(){
			var el = $(this);
			switch(this.type){
				case "hidden":
				case "text":
				case "select-one":
				case "select-multiple":
				case "textarea":
					var name = this.name.match(/(.+)\[([^\]]*)\]$/);
					if(name){
						if(name[2]){
							if(data[name[1]]==null) data[name[1]]={};
							data[name[1]][name[2]] = el.val();
						}else{
							if(data[name[1]]==null) data[name[1]]=[];
							data[name[1]].push(el.val());
						}
					}else{
						data[this.name] = el.val();
					}
					break;
				case "checkbox":
//					var name = this.name.match(/(.+)\[([^\]]+)\]$/);
//					console.log(name)
//					if(data[this.name]==null) data[this.name]=[];
//					if(this.checked) data[this.name].push(el.val());
//					break;
				case "radio":
					var name = this.name.match(/(.+)\[([^\]]+)\]$/);
					if(name){
						if(data[name[1]]==null) data[name[1]]={};
						if(this.checked) data[name[1]][name[2]] = el.val();
					}else{
						if(this.checked) data[this.name] = el.val();
					}
					break;
			}
		});

		return data;
	}

	this.setCookie =  function(name,value,expire,path,domain,secure){
		var cookie_string = name + "=" + escape ( value );

	  	if ( expire ){

		    if( !(expire instanceof Date) ){
				var expires = new Date ( expire );
			}

			if( expires ){
				cookie_string += "; expires=" + expires.toGMTString();
			}
		}

	  	if ( path ){
	        cookie_string += "; path=" + escape ( path );
		}

	  	if ( domain ){
	        cookie_string += "; domain=" + escape ( domain );
	  	}

	  	if ( secure ){
	        cookie_string += "; secure";
	  }
	  document.cookie = cookie_string;
	}

	this.wordWrap = function(selector){

	    var larg_total;
		var larg_carac;
		var quant_quebra;
		var pos_quebra;
	    var elementos;
		var quem;
		var caracs;
		var texto;
		var display_orig;

	    if(!selector){
	    	elementos = $("p.word-wrap").get();
	    } else {
	    	elementos = $(selector).get();
	    }

	    for(var i=0; i<elementos.length;i++){

	            quem = elementos[i];

	            quem.innerHTML = String(quem.innerHTML).replace(/ /g,"^"); //"�"
	            texto = String(quem.innerHTML);

	            quem.innerHTML = " ";

	            display_orig = quem.style.display;
	            quem.style.display="block";
	            larg_oficial = quem.offsetWidth;

					if(!document.all) { quem.style.display="table"; }

	            quem.innerHTML = texto;
	            larg_total = quem.offsetWidth;

	            pos_quebra = 0;
	            caracs = texto.length;
	            texto = texto.replace(/\^/g," ");
	            larg_carac = larg_total / caracs;
	            if(larg_total > larg_oficial){
	                quant_quebra = parseInt(larg_oficial / larg_carac);
	                quant_quebra = quant_quebra - (parseInt(quant_quebra / 6)); //quanto menor o num, maior a garantia;
	                quem.innerHTML = "";
	                while(pos_quebra <= caracs){
	                    quem.innerHTML = quem.innerHTML + texto.substring(pos_quebra,pos_quebra + quant_quebra) + " ";
	                    pos_quebra = pos_quebra + quant_quebra;
	                }
	            }else{
	                quem.innerHTML = texto;
	            }//end if do larg_total>larg_oficial
	            quem.style.display = display_orig;

	    }//end for loop dos elementos
	}

	//this.maxChars = function(inputSelector,charsLeftSelector){
	//	$cl 	= $(charsLeftSelector);
	//	$input  = $(inputSelector);
	//
	//	var maxChars = parseInt ( $cl.html() );
	//	$input.attr('maxlength',maxChars);
	//
	//	function check(){
	//		var cc = $(this).val().length;
	//		if( cc >= maxChars ) {
	//			return false;
	//		} else {
	//			$input.val($input.val().substr(0,maxChars));
	//		}
	//	}
	//
	//	function update(){
	//		$cl.html( String( maxChars - $(this).val().length ) );
	//	}
	//
	//	$input.keypress(check).keyup(update).change(check).change(update);
	//}

	/**
	 *
	 * @param {Object} inputSelector
	 * @param {Object} charsLeftSelector - optional
	 */

	this.maxChars = function(inputSelector,charsLeftSelector){

		var $cl,$input;

		if( charsLeftSelector ){
			$cl 	= $(charsLeftSelector);
		}

		$input  = $(inputSelector);

		var maxChars = 0;

		if( charsLeftSelector ){
			maxChars = parseInt ( $cl.html() );
			$input.attr('maxlength',maxChars);
		} else {
			maxChars = $input.attr('maxlength');
		}

		function check( obj ){
			var txt = $(obj).val()
			var cc = txt.length;
			if( cc > maxChars ) {
				$input.val(txt.substr(0,maxChars));
				return false;
			} else {
				return cc;
			}
		}

		function update(){
			var len;
			if( len = check( this ) ){
				var v = String( maxChars - len );

				if( charsLeftSelector ){
					$cl.html( v );
				}
			}

		}

		$input.keydown(update).change(update).blur(update);
	}

	this.showConfirmation = function(confirmSelector,showTime,callback){
		var _showTime = showTime ? showTime : 5000;
		var _callback = callback ? callback : function(){};
		$msg = $(confirmSelector);
		$msg.slideToggle('fast',function(){window.setTimeout(function(){$msg.slideToggle('fast',callback);},_showTime);});
	}

	this.getSWF = function(movieName) {
	    if (navigator.appName.indexOf("Microsoft") != -1) {
	        return window[movieName]
	    }
	    else {
	        return document[movieName]
	    }
	}

	var __trimDefaultCharsList = "\\s";

	this.stringLeftTrim = function(string,chars){
		if(!chars){
			var chars = __trimDefaultCharsList;
		}
		var exp = new RegExp("^("+chars+")+","g");
		try {
			return string.replace(exp,'');
		} catch( e ) {
			return '';
		}
	}

	this.stringRightTrim = function(string,chars){
		if(!chars){
			var chars = __trimDefaultCharsList;
		}
		var exp = new RegExp("("+chars+")+$","g");
		try {
			return string.replace(exp,'');
		} catch( e ){
			return '';
		}
	}

	this.stringTrim = function(string,chars){
		if(!chars){
			var chars = __trimDefaultCharsList;
		}
	return _self.stringRightTrim(_self.stringLeftTrim(string,chars),chars);
	}

	this.imageReloader = function( src ){

		if( $.browser.mozilla ){
			var $iframe = $("<iframe/>").css({position:'absolute',left:-1000, top:-1000});

			$('body').append($iframe);

				function removeIframe(){
					if( $iframe.get(0).contentWindow.location.href == src ){
						$iframe.replaceWith('');
					}
				}

				if(self.attachEvent){
					$iframe.get(0).attachEvent('onload', removeIframe);
			    } else {
					$iframe.get(0).addEventListener('load', removeIframe, false);
			    }

			$iframe.get(0).contentWindow.location.href=src;
			$iframe.get(0).location.reload( true );
		} else {
			top.location.reload( true );
		}
	}

	this.redirNoFollow = function( pth, uid, useConversionTag ) {
		// cloack the link, so google cannot guess this is a link [STYLR-771]
		var prefixUrl = '';
//		if( productOut == 1 ) { // styler product out
//			prefixUrl = STYLER_SHOP_DOMAIN + '/product-out/';
			// call GAdWords campaign conversion
			if( useConversionTag == 1 ) {
				setTimeout( function klicktracking()
					{ var conversiontag = document.getElementById('trackingpixel').innerHTML
						= '<iframe src="/googleStylrAdWordsCampaign.html" style="border:none;width:1px;height:1px;" marginheight="0" marginwidth="0" frameborder="0"></iframe>';
					}, 2000 );
			}
//		}
//		pth = Base64.decode(window.hiddenlinks[uid]);
		pth = Base64.decode(uid);
		if( !pth ) {
			location.href='';
		} else {
			location.href= pth;
		}
	}

	this.openNewWindow = function( path, uid, useConversionTag ){
		// cloack the link, so google cannot guess this is a link [STYLR-771]
		var prefixUrl = '';
//		if( productOut == 1 ) { // styler product out
//			prefixUrl = STYLER_SHOP_DOMAIN + '/product-out/';
			// call GAdWords campaign conversion
			if( useConversionTag == 1 ) {
				setTimeout( function klicktracking()
					{ var conversiontag = document.getElementById('trackingpixel').innerHTML
						= '<iframe src="/googleStylrAdWordsCampaign.html" style="border:none;width:1px;height:1px;" marginheight="0" marginwidth="0" frameborder="0"></iframe>';
					}, 2000 );
			}
//		}

//        path = Base64.decode(window.hiddenlinks[uid]);
        path = Base64.decode(uid);
		var $hiddenForm = $("<form action='"+path+"' target='_blank'></form>");
		$('body').append($hiddenForm.hide());
		$hiddenForm.submit();
		$hiddenForm.replaceWith('');
	}

    this.isArray = function( variable ){
	return variable.constructor == Array;
    }

    this.isObject = function( variable ){
	return variable.constructor == Object;
    }

    this.isString = function( variable ){
	return variable.constructor == String;
    }

    this.isNumber = function( variable ){
	return variable.constructor == Number;
    }

	this.isEmail = function( string ){
		string = this.stringTrim(string);
		return /[a-z][a-z0-9\-\_\.]+[a-z0-9]\@[a-z0-9]([a-z0-9\-\_\.]*[a-z0-9])+\.[a-z]{2,}/.test( string );
	}

	this.emoticonsReplace = function( content, emoticons ){
		var emoticons = emoticons || Config.emoticonsPatternsCKE;

		for( var e in emoticons ) {

			var emo 	= emoticons[e];
			var pattern = "";
				if( emo.pattern.constructor == Array ){
					var patterns = emo.pattern;
					var tmp = [];
					for( var i in patterns ){
						tmp.push("("+sys.pregQuote(patterns[i])+")");
					}
					pattern = tmp.join("|");
				} else {
					pattern = sys.pregQuote( emo.pattern );
				}

				var regexp = new RegExp(pattern,'gi');

			content = content.replace( regexp, '<img src="'+emo.src+'" alt="'+emo.alt+'">' );
		}
		return content;
	}

}

$.fn.simpleTabs = function(){

	$(this).each(function(){
		$(this).click( function(){

			var $tabsGroup = $(this).parent().children();

			$tabsGroup.filter('.active').hide();
			$tabsGroup.filter('.no_active').show();

			$tabsGroup.each(function(){
				$( $(this).attr('rel') ).hide();
			});

			$tabsGroup.filter('[rel="'+$(this).attr('rel')+'"].no_active').hide();
			$tabsGroup.filter('[rel="'+$(this).attr('rel')+'"].active').show();

			$( $(this).attr('rel') ).show();

			if( window['plg_page_pixels'] != undefined ){
				plg_page_pixels.redisplayPixels();
			}
		} );
	});
};

$.fn.showEmoticons = function( emoticons ) {

	$( this ).each( function( index, element ) {
		var body 	= $( element );
		var content	= body.html();
		body.html( sys.emoticonsReplace(content,emoticons) );
	} );
}

$.fn.defaultText = function( text, toggleClass ) {

	if( text == undefined ){
		text = '';
	}

	if( toggleClass == undefined ){
		toggleClass = '';
	}

	$( this ).each( function() {

		var textAccesor = 'text';

		switch( true ){
			case $(this).is('input'):
				textAccesor = 'val';
				break;
		}

		$(this)
			.data('defaultText',{ text: text, toggleClass: toggleClass, accessor: textAccesor })
			.focus(function(){
				var data = $(this).data('defaultText');
				if( $(this)[data.accessor]() == data.text ){
					$(this).removeClass( data.toggleClass );
					$(this)[data.accessor]('');
				}
			})
			.blur(function(){
				var data = $(this).data('defaultText');
				if( $(this)[data.accessor]() == '' ){
					$(this).addClass( data.toggleClass );
					$(this)[data.accessor]( data.text );
				}
			});

			var $field = $(this);

			$( $(this).get(0).form).submit( function(){
				$field.triggerHandler('focus');
			} );

	} ).triggerHandler('blur');
}

$.fn.prepareImgLazyLoad = function( srcAttr ){
	var srcAttr = srcAttr || 'ill';

	return this.each( function( index, element ) {
		var $imgs = $('img', $(element));
		if( $imgs.size() > 0 ){
			$imgs.each(function(){
				var $img = $(this);
				$img.attr( srcAttr, $img.attr( 'src' ) );
				$img.attr( 'src', MEDIA_DOMAIN+"/addons/common/pics/dummy.gif" );
			});
		}
	} );
}

$.fn.imgLazyLoad = function( srcAttr, onload ) {
	var srcAttr = srcAttr || 'ill';

	return this.each( function( index, element ) {
		var $imgs = $('img', $(element));
		if( $imgs.size() > 0 ) {
			$imgs.each(function(){
				var $img = $(this);
				if( $img.attr( srcAttr ) ){
					if( onload ){
                        $img.bind('load error',function(){
                            onload.apply(this, arguments );
                        });
					}

					$img.attr( 'src', $img.attr( srcAttr ) );
					$img.attr( srcAttr, '' );
				} else {
                    if( onload ){
                        onload.apply(this,[]);
                    }
                }
			});
		}
	} );
}

$(document).ready( function() {

	$('.jQhiddableSwitcher').click( function() {
		$(this).parent().next().toggle();
	} );

	$('.jQ_simpleTab').simpleTabs();
});






