Int = parseInt;
Float = parseFloat;
enc = encodeURIComponent;
if (!window.console) {
	window.console = {
		log: function(){}
	};
};
utils = {
	'Date': {
		format: function(date){
			try{
				var y = date.getFullYear().toString(),m = (date.getMonth()+1).toString(),d = date.getDate().toString(),
				date = new Date(date);
				return y+'/'+(m.length<2 ? ('0'+m):m)+'/'+(d.length<2 ? ('0'+d):d);
			}catch(e){
				return '';
			}
		}
	},
	'String': {
		/*
			将一个字符串分割为长度为n的多个字符串，并对每个字符串进行filter处理
			例：
				DayParting.StringUtils.splitMap('1122334411223',2,function(str){
					return parseInt(str).toString(2);
				});
				// => ["1011", "10110", "100001", "101100", "1011", "10110", "11"]
		*/
		splitMap: function(str,n,filter) {
			if(typeof str == 'string'){
				var p = 0,result = [];
				for (var i=0; i < str.length/n; i++) {
					var s = str.substr(i*n,n);
					result.push($.isFunction(filter) ? filter(s) : s);
				};
				return result;
			}
		},
		binaryToHex: function(data) {
			return this.splitMap(data,24,function(d){
				return this.fill(parseInt(d,2).toString(16),6,'0');
			}.bind(this)).join('');
		},
		hexToBinary: function(str){
			return this.splitMap(str,6,function(str){
				return this.fill(parseInt(str,16).toString(2),24,'0');
			}.bind(this));
		},
		/*
			在字符串前面补充字符，直到长度达到n
			例如：
				DayParting.StringUtils.fill('A',10,'0');	//=> "000000000A"
		*/
		fill: function(str,n,fillWith){
			var l = str.length,s = str;
			while(l < n){
				s = fillWith+s;
				l++;
			}
			return s;
		},
		/*
			格式化数据，方便页面显示，比如下面的序列
				111111000000111111000000
			格式化之后的格式为：
				[
					//周一
					[
						[0,5],[12,17]
					],

				]
		*/
        formatDayPartingSettings: function(selected,isVal){
            var result = [];
            if (isVal) {
                selected = utils.String.splitMap(selected,24);
                if (selected.join('').indexOf('1') + 1||selected.join('').indexOf('0') + 1) {
                    for (var i=0; i < selected.length; i++) {
                        var str = selected[i],index = 0,r = null,arr = [],temp = str;
                        while(r = temp.match(/[1]+/)){
                            var start = r.index+index;
                            arr.push([start]);
                            index = start + 1;
                            temp = str.substr(index);
                        }
                        result.push(arr);
                    };
                };
            }else{
                selected = utils.String.splitMap(selected,24);
                if (selected.join('').indexOf('1') + 1||selected.join('').indexOf('0') + 1) {
                    for (var i=0; i < selected.length; i++) {
                        var str = selected[i],index = 0,r = null,arr = [],temp = str;
                        while(r = temp.match(/[1]+/)){
                            var start = r.index+index,end = start + r[0].length - 1;
                            arr.push([start,end]);
                            index = end + 1;
                            temp = str.substr(index);
                        }
                        result.push(arr);
                    };
                }
            }
			return result;
		}
	}
}
Array.prototype.indexOf = Array.prototype.indexOf || function(item){
	for (var i=0; i < this.length; i++) {
		if(this[i]===item){
			return i;
		}
	};
	return -1;
}
String.prototype.escapeHTML = function(){
	return this.replace(/\&/g,'&amp;').replace(/\>/g,'&gt;').replace(/\</g,'&lt;').replace(/\"/g,'&quot;');
}
String.prototype.trim = String.prototype.trim || function(){
	return this.match(/^\s*(.*?)\s*$/)[1];
};

function hideFlash(){
	var el = $('.flash-success,.flash-fail');
	el.fadeOut(function(){
		el.remove();
	});
}
function ShowFlash(success,msg,description,links){
	var html = '<div class="'+(success?'flash-success':'flash-fail')+'">'+
		'<a class="close-tag"></a>'+
		'<div class="left"><div class="ico"></div></div>'+
		'<div class="right">'+
			'<div class="title">'+msg+'</div>'+
		'</div>';
	if (description) {
		html += '<div class="description" style="padding:0 20px;">'+description+'</div>';
	};
	if (links) {
		html += '<div class="links">';
		for (var i=0; i < links.length; i++) {
			html += '<a href="'+links[i].href+'">'+links[i].text+'</a>';
		};
		html += '</div>';
	};
	html +='</div>';
	var flash = $(html).appendTo(document.body).show();
	flash.css({
		left:($(window).width() - flash.width())/2 + 'px'
	});
	flash.find('.close-tag').click(function(){
		flash.fadeOut(function(){
			flash.remove();
		});
	});
	setTimeout(function(){
		flash.fadeOut(function(){
			flash.remove();
		});
	},5e3);
}
function RenderTemplate(template, obj, obj_name) {
	// render [#=something#]
	function __(template, obj, obj_name) {
		eval("var " + obj_name + "=obj");
		var m, t = template;
		while (m = t.match(/\[#\=(.*?)#\]/)) {
			t = t.replace(m[0], eval(m[1]));
		}
		return t;
	};
	// blablabla
	var m, t = template, frags = [], commands = [], p = 0;
	// divide the template
	while (m = t.match(/\[#([^\=].*?)#\]/)) {
		frags.push(t.substr(0, t.indexOf(m[0])));
		commands.push(m[1]);
		t = t.substr(t.indexOf(m[0]) + m[0].length);
	}
	frags.push(t);
	// combine the frags
	var result = "", str = "";
	for ( var _ = 0; _ < commands.length; _++) {
		if (frags[_].trim() != "")
			str += "result+=__('" + frags[_] + "',obj,obj_name);";
		str += commands[_];
	}
	;
	str += "result+=__('" + frags[_] + "',obj,obj_name);";
	// execute
	eval(str);
	return result;
}

Function.prototype.bind = function() {
	function generateArray(ori) {
		var args = [];
		for ( var i = 0; i < ori.length; ++i)
			args[i] = ori[i];
		return args;
	}
	// if (arguments.length < 2 && typeof(arguments[0]) == "undefined") return
	// this;
	var args = generateArray(arguments);
	var __method = this, object = args.shift();
	return function() {
		var _args = generateArray(arguments);
		return __method.apply(object, args.concat(_args));
	};
};

function emptyOnUnload() {
	window.onbeforeunload = function() {
	};
}

function redirectConfirm(url,msg){
	var a = confirm(msg,function(result){
		if (result) {
			location.href = url;
		};
	});
	if (a) {
		location.href = url;
	};
}

var removeConfirm = redirectConfirm;

function cancelFormConfirm(cancel,i, errorInfo) {
	var msg = errorInfo || ipyLang.cancelConfirm;
	msg = '您确定取消对页面的操作？';
	if ($(cancel).attr('data-value') == 'false') {
		var a = confirm(msg,function(result){
			if (result) {
				try {
					this.emptyOnUnload();
					history.go(i);
				} catch (e) {
				}
			};
		}.bind(this));
		if (a) {
			try {
				this.emptyOnUnload();
				history.go(i);
			} catch (e) {
			}
		}
	}else{
		emptyOnUnload();
		history.go(i);
	}
	
	
}
function formChange(f){
	$('#'+f+' input,select,textarea').one('change',function(){
		$('input[name="formCancel"]').attr('data-value',false)	
	});
}
function cancelToUrlConfirm(cancel,url, errorInfo) {
	var msg = errorInfo || ipyLang.cancelConfirm;
	msg = '您确定取消对页面的操作？';
	if ($(cancel).attr('data-value') == 'false') {
		var a = confirm(msg,function(result){
			if (result) {
				try {
					this.emptyOnUnload();
					self.location.href=url;
				} catch (e) {
				}
			};
		}.bind(this));
		if (a) {
			try {
				this.emptyOnUnload();
				self.location.href=url;
			} catch (e) {
			}
		}
	}else{
		emptyOnUnload();
		self.location.href=url;
	}
}
var cookie = {
    set: function(b, e, a, c, d) {
        z = new Date;
        z.setTime(z.getTime() + (a || 0));
		var x = b + "=" + enc(e || "") + (a ? ("; expires=" + z.toGMTString()) : '') + ";path=/; domain=ipinyou.com" + (d ? "; secure": "");
        document.cookie = x;
    },
    get: function(b) {
        return (b = document.cookie.match(RegExp("(^|;)\\s*" + b + "=([^;]*)", "i"))) ? decodeURIComponent(b[2]) : ""
    }
};
