/**
 * @class The MIXAM global namespace
 */

if (typeof MIXAM == "undefined") {
    var MIXAM = {
		offering :{},
		util:{},
		widget: {},
		regional: {}
    };
}

$E = YAHOO.util.Event;
$D = YAHOO.util.Dom;
$ = $D.get;

window.console = typeof console == "undefined" ? {
  log: function() { },
  info: function() { },
  debug: function() { }
} : console;


(function(){

	String.prototype.trim = function(){
		return this.replace(/(^\s*)|(\s*$)/g, "");
	};

	String.prototype.padl = function(ch, length){
		var text = new String(this);

	    for (var i = text.length; i < length; i++){
			text = ch + text;
		}
	    return text;
	};

	if (!Array.prototype.forEach) {
		Array.prototype.forEach = function (fun) {
			var len = this.length;

			var thisp = arguments[1];
			for (var i = 0; i < len; i++){
			  if (i in this)
			    fun.call(thisp, this[i], i, this);
			}
		};
	}
})();


MIXAM.util.Browser = new function(){
    var pairs = window.location.search.substring(1).split( "&" ),
		ua = navigator.userAgent.toLowerCase(),
		key,
		value,
		parameters;

	this.isOpera = (ua.indexOf('opera') > -1);

	this.isSafari = (ua.indexOf('webkit') > -1);

	this.isIE = (window.ActiveXObject);

	this.isIE7 = (ua.indexOf('msie 7') > -1);

	this.isGecko = !this.isSafari && (ua.indexOf('gecko') > -1);

	if(ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1){
	    this.isWindows = true;
	}else if(ua.indexOf("macintosh") != -1){
	    this.isMac = true;
	}

	parameters = {};
    this.parameters = parameters;
    pairs.forEach(function(value, index, instance){
		var pos = value.indexOf( "=" ), val, key;

        if ( pos > 0 ){
			key = unescape(value.substring(0, pos) );
			val = unescape(value.substring(pos + 1) );
			parameters[key] = val;
		}
    });

	if(this.isIE && !this.isIE8){
        try{
            document.execCommand("BackgroundImageCache", false, true);
        }catch(e){}
    }

    this.getAnchor = function(){
        var re = /#([^#]+)$/;
        return re.test(window.location.href) ?
               re.exec(window.location.href)[1] :
                 null;
    };
};

/**
 * defaulu US regional settings
 */

MIXAM.regional = {
	number: {
		decimalSymbol: ".",
		numberOfDecimalDigits: 2,
		digitGroupingSymbol: ",",
		negativeSign: "-",
		example: "123,456,789.00"
	},

	currency: {
		symbol: "$",
		position: "pre"
	},

	msisdn:{
		format: "aaannnnnnno",
		example: "51212345678"
	},

	time: {
		format: "h:mm:ss tt",
		separator: ":",
		symbolAM: "AM",
		symbolPM: "PM",
		example: "3:44:57 PM"
	},

	date: {
		'short': {
			format: "m/d/yyyy",
			example: "4/13/2007"
		},

		'long': {
			format: "DDDD, MMMM dd, yyyy",
			example: "Friday, April 13, 2007"
		},

		separator: "/",

		months: {
			'char':  ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
			'short': ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
			medium: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
			'long':  ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
		},

		weekdays: {
			'char': ["S", "M", "T", "W", "T", "F", "S"],
			'short': ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
			medium: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
			'long': ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
		},

		calendar: {
			DATE_FORMAT_TEMPLATE: "mm/dd/yyyy",
			DATE_FORMAT_MONTH_TEMPLATE: "mm/yyyy"
		}
	},

    ip: {
        errorCellOutOfScopeNaN: "Cell %s must be a valid number",
        errorCellOutOfScopeOverflow: "Cell %s can't be bigger than 255",
        errorFormatError: "The Field is not in IP Address format (999.999.999.999)"
    },

    url: {
        errorMissingProtocol: "Invalid URL: The protocol (http://, https://) is missing from URL",
        errorMissingHost: "Invalid URL: The host (www.domain.com) is missing from URL",
        errorInvalidUrl: "Invalid URL Format: the address should look like 'http://www.domain.com'"
    },

    password: {
		best: "Best",
		strong: "Strong",
		medium: "Medium",
		weak: "Weak",
        errorInvalidPassword: "Password field contains invalid value",
        errorComparePassword: "The two copies of the password must be identical",
        errorContainsUsername: "Your password may not contain the user name or large portions of it"
    },

    dialog: {
        messageCloseModuleCaption: "Close",
        messageCloseModuleTitle: "Remove this message"
    },

    email: {
        errorInvalidEmail: "The address is not a valid email address"
	},

    tabcontrol: {
		active: "Active"
	},
    display :{
        promote : {
            "get" : "get",
            "for" : "for"
        },
        tooltip : {
            multipostfix : "s",
            weight : "kg"
        },
        panel : {
            title : "Switch currency"
        }
    }
}

MIXAM.util.textToCharCodes = function(text){
	var result = "",
		i,
		len = text.length;

	for(i = 0; i < len; i++){
		result += text.charCodeAt(i) + (i < (len - 1) ? "," : "");
	}
	return result;
};

MIXAM.util.blink = function(element, func){
    var animl,
        currentBkg = $D.getStyle(element, 'backgroundColor'),
        background =  currentBkg && currentBkg != "transparent" ? currentBkg : 'rgb(228, 242, 245)';

    if (YAHOO.util.ColorAnim){
        anim = new YAHOO.util.ColorAnim(element,
            { backgroundColor: { to:  'rgb(255, 245, 143)' } }, 0.7, YAHOO.util.Easing.easeIn);
        anim.onComplete.subscribe( function() {
                var anim = new YAHOO.util.ColorAnim(element,
                    { backgroundColor: { to:  background } }, 0.5, YAHOO.util.Easing.easeOut);
                anim.onComplete.subscribe(function(){
                    $D.setStyle(element, "backgroundColor", currentBkg);
                });
                if (func){
                    anim.onComplete.subscribe(func);
                }
                anim.setAttribute('useSeconds', false);
                anim.animate();
            }
        );
        anim.setAttribute('useSeconds', false);
        anim.animate();
    }
}

MIXAM.util.formatText = function(text){
    if (text){
        text = text.replace(/~P~/gi, "<p>").replace(/~@P~/gi, "</p>").
                replace(/~STRONG~/gi, "<strong>").replace(/~@STRONG~/gi, "</strong>").
                replace(/~BLUE~/gi, "<strong class='blue'>").replace(/~@BLUE~/gi, "</strong>").
                replace(/~RED~/gi, "<strong class='red'>").replace(/~@RED~/gi, "</strong>");
    }
    return text;
}

MIXAM.util.Cookie = new function() {

	/**
	 * Reads the content of HTTP cookie into the object.
	 * @param {String} name The name of the HTTP cookie.
	 * @return {String} The Value of the cookie or the value of defaultValue or null.
	 */
	this.read = function(name, defaultValue) {
		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 c.substring(nameEQ.length, c.length).replace(/^null$/, "");
			}
		}
		return defaultValue;
	};

	/**
	 * Writes the content of value into HTTP cookie named
	 * name, expires after 'days' days.
	 * @param {String} name The name of the HTTP cookie.
	 * @param {String} value The value of the HTTP cookie.
	 * @param {Number} days Expires after n days.
	 */
	this.write = function(name, value, days, path) {
		var expires = "";
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+ (days * 24 * 60 * 60 * 1000));
			expires = "; expires=" + date.toGMTString();
		}
		document.cookie = name + "=" + value + expires + "; path=" + (path || "/");
	}
};


MIXAM.util.Format = {
	formatNumber: function(text, round){
		var decimalSymbol = ".",
			separator = ",",
			i, f,
			j = 0,
			iPos,
			newText = "";

		if (text){
			if (round){
				text = parseInt(text).toString();
				iPos = text.length
			} else {
				f = parseFloat(text.toString());
				text = (Math.round(f * 100) / 100).toString();
				iPos = text.indexOf(decimalSymbol);
				if (iPos >= 0){
					newText = (text + "000").substr(iPos, 3);
				}else{
					newText = ".00";
					iPos = text.length
				}
			}
			for (i = iPos - 1; i >= 0; i--){
				newText = text.charAt(i) + newText;
				if (++j % 3 == 0 && i){
					newText = separator + newText;
				}
			}
			return newText.replace(/-,/gi, "-");
		}
	},

	formatNumber2: function(num, decimal){

		function addSeperator(numText){
			var x = numText.toString().split('.'),
			    x1 = x[0],
			    x2 = x.length > 1 ? '.' + x[1] : '',
			    rgx = /(\d+)(\d{3})/;

			while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
			}
			return x1 + x2;
		}

		if (typeof num == "number"){

			if (num.toFixed){
				return addSeperator(num.toFixed(decimal));
			} else {
				num.toString();
			}
		}

		return "";
	}

};




