/**
 * @author Cosmin Harangus
 */
var A25Core={
	init:function(){
		jQuery(document).pngFix();
		A25Core._bindHistory();
		A25Core.__fixLinkButons();
	},
	__fixLinkButons:function(){
		//Link Button IE fix
		jQuery("a button").live("click",function(){ window.location = jQuery(this).parent('a')[0].href; return false;});
	},
	
	__isEmail:function(email){
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   		return emailPattern.test(email);
	},
	
	__isURL: function(url) {
//		var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
		var regexp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
		return regexp.test(url);
	},

	__validate:function(container, url, f){
		jQuery(container + " .error").html('');jQuery(container + " em").html('');
		var _data={};
		jQuery(container + " input").each(function(){
			if (jQuery(this).attr('type').toLowerCase() == 'checkbox'){
				if (jQuery(this).attr('checked')){
					_data[this.name] = jQuery(this).val();
				}
			}else{
				if (jQuery(this).attr('type').toLowerCase() == 'radio'){
					if (jQuery(this).attr('checked')){
						_data[this.name] = jQuery(this).val();
					}
				}else{
					_data[this.name] = jQuery(this).val();
				}
			}
		});
		jQuery(container + " select").each(function(){
			if (jQuery(this).attr('multiple')){
				if (!_data[this.name]) _data[this.name] = {};
				_data[this.name][_data.length] = jQuery(this).find('option:selected').val();
			}else{
				_data[this.name] = jQuery(this).find('option:selected').val();
			}
		});
		jQuery(container + " textarea").each(function(){
			_data[this.name] = jQuery(this).val();
		});
		if (jQuery('base').length) url = jQuery('base')[0].href+url;
		jQuery.ajax({
			async:true,
			type:'POST',
			'url':url,
			data:_data,
			dataType:'json',
			success: function(resp, status){
				jQuery(container + " label em").html('');
				if (!resp.success){
					jQuery.each(resp.errors, function(k,v){
						jQuery(container + ' [name="'+k+'"]').parent().next('em').html(v);
					});
				}
				f(resp);
			},
			error:function(a,b,c){
				alert(c);
			}
		});
	},
	__submitForm:function(form, name, value){
        if (!value) value=1;
		jQuery("#submitForm").remove();
		jQuery(form).prepend('<input type="hidden" value="'+value+'" name="'+name+'" id="submitForm" />');
		jQuery(form).submit();
	},
	__validateForm:function(__wrap, url, f){
		$(__wrap+" button[name='__submit']").click(function(){
			var name=jQuery(this).attr('name');
			var val=jQuery(this).val();
			A25Core.__validate(__wrap, url, function(resp){
				if (resp.success){
					A25Core.__submitForm(__wrap+' form', name, val);
				}else if (f) f(resp);
			});
			return false;
		});
	},
	__htmlToJson:function(html){
		try{
			eval("resp="+html);
		}catch(_e){resp={success:true, html_response:html};}
		return resp;
	},
	_bindHistory:function(){
		jQuery.History.bind(function(state){
			//var options = Base64.decode(state).split(';');
			var options = state.split(';');
			var cmd = options[0].split('-');
			
			//	notify page of currently loaded view
			try {
				if (Page) Page.setCurrentView(cmd[1]);
			}catch(_e){}
				
			switch(cmd[0]) {
				case "load":{
					jQuery(options[1]).load(options[2]);
				}break;
				case "fetch":{
					
				}break;
				case "get":{
					
				}break;
			}
		}); 
	},
	alert:function(title, message, f){
		alert(message);
		if (f) f(true);
	},
	confirm:function(message,f){
		var answer=confirm(message);
		if (f) f(answer);
		return answer;
	},
	iframeAjax:function(wrap,url,data,f){
		jQuery(wrap+" input, "+wrap+" textarea, "+wrap+" select").ajaxFileUpload({
			'url': url,
			'data': data,
			dataType: 'html',
			success: function(html){
				resp = A25Core.__htmlToJson(html);
				if (f) f(resp);
			}
		});
	},
	history:{
		refresh:function(){window.history.go(0);}
	},
	__showPopUp:function(popUpId){
		jQuery("a[href='"+popUpId+"']").click(function(){
			__createDialog(popUpId, {height:300});
			__openDialog(popUpId);
			jQuery(popUpId+" button").unbind('click');
			jQuery(popUpId+" button").click(function(){
				__closeDialog(popUpId);
				return false;
			});
			return false;
		});
	}
};
//translate a string localy
function _(str){return str;};
function __tpl(name, data, _to){
	jQuery.get('scripts/templates/'+name, function(tpl){
		jQuery.jqoteTpl(tpl, data).appendTo(_to);
    },'text');
};
//translate an array of strings via ajax
function _T(data){return data;};
function __openDialog(select){jQuery(select).dialog('open');};
function __closeDialog(select){jQuery(select).dialog('close');};
function __createDialog(select, options){
	var defaults = {
		autoOpen:false,
		bgiframe: true,
		width:400,
		close:function(){jQuery(this).dialog('destroy');}
	};
	var settings = jQuery.extend({}, defaults, options);
	jQuery(select).dialog(settings);
};
//Numeric validation
function isNumeric(value) {
	if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
	return true;
};
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
};
//opens a link in a smaler window
function popup(mylink, windowname, width, height){
	if (! window.focus)return true;
	var href;
	if (typeof(mylink) == 'string')
		href=mylink;
	else
	href=mylink.href;
	window.open(href, windowname, 'width='+width+',height='+height+',scrollbars=yes', 'resizable = 0');
	return false;
}
//generates a randim string
function randomString(length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = length;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

//
//function accountingFormat(inputNumber, withCents){
//	inputNumber = inputNumber.replace(/[$]/g,'');
//	var aux = inputNumber.split('.');
//	var number = aux[0];
//	number = number.replace(/[,]/gi,'');
//	var rez = '';
//	var sep = '';
//	var nr = Number(number);
//	if (nr){
//		while (number != 0){
////			rez = number%1000 + sep + rez;
//			rez = number<0?(-number)%1000 + sep + rez:number%1000 + sep + rez;
//			sep = ',';
//			number = Math.floor(number/1000);
//		}
//		//alert(rez);
//		if (withCents == true && aux.length == 2) return '$'+rez+'.'+aux[1];
//		else return '$'+rez;
//	}
//}

function accountingFormat(inputNumber, withCents){
	inputNumber = inputNumber.replace(/[$]/g,'');
	var aux = inputNumber.split('.');
	var number = aux[0];
	number = number.replace(/[,]/gi,'');
	var rez = Number(number).numberFormat('0,0');

	if (withCents == true && aux.length == 2) return '$'+rez+'.'+aux[1];
	else return '$'+rez;

}
//function accountingFormat(amount, withCents){
//	amount.replace(/[$]/,'');
//	if (amount.indexOf('-') != -1){
//		var sign = '-';
//		amount.replace(/[-]/,'');
//	}  
//	else{
//		var sign = '';
//	}
//	$decimals = '';
//	var pos = amount.indexOf('.');
//	if (pos != -1){
//		var decimals = amount.substr(pos, amount.length);
//		amount = amount.substr(pos, amount.length);
//	}
//	var rez = '';
//	var sep = '';
//	while (amount != 0){
//		var aux = amount % 1000;
//		rez = aux + sep + rez;
//		sep = ',';
//		amount = Math.floor(amount/1000);
//	}
//	return '$'+sign+rez+decimals;
//}
//function accountingFormat(inputNumber, withCents){
//	inputNumber = inputNumber.replace(/[$]/g,'');
//	var aux = inputNumber.split('.');
//	var number = aux[0];
//	number = number.replace(/[,]/gi,'');
//	var rez = Number(number).numberFormat('0,0');
//
//	if (withCents == true && aux.length == 2) return '$'+rez+'.'+aux[1];
//	else return '$'+rez;
//
//}

//Length of Javascript Associative Array
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

//Other util
// Simulates PHP's date function
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return"Not Yet Supported";},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return"Not Yet Supported";},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};
