var js_version = '8bc5ac7db6a36f99';

//From Gmail.js

var agt = navigator.userAgent.toLowerCase();
var is_op = (agt.indexOf("opera") != -1);
var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op;
var is_ie5 = (agt.indexOf("msie 5") != -1) && document.all && !is_op;
var is_ie7 = (agt.indexOf("msie 7") != -1) && document.all && !is_op;
var is_mac = (agt.indexOf("mac") != -1);
var is_gk = (agt.indexOf("gecko") != -1);
var is_sf = (agt.indexOf("safari") != -1);
var is_safari = (agt.indexOf("safari") != -1);
var is_nav = !is_ie && !is_safari && (agt.indexOf("mozilla") != -1);
var FIRST_BUTTON = (is_safari || is_ie) ? 1 : 0;
var is_xp = ((agt.indexOf("windows nt 5.1") != -1)
	     || (agt.indexOf("windows xp") != -1));
var is_2k = ((agt.indexOf("windows nt 5.0") != -1)
	     || (agt.indexOf("windows 2000") != -1));



function AssertTrue(expr)
{
    if (!expr) {
	DumpError("Assertion failed.\n");
	throw "Assertion failed.";
    }
}


function AssertEquals(val1, val2)
{
    if (val1 != val2) {
	DumpError("AssertEquals failed: <" + val1 + "> != <" + val2 + ">");
	throw "Assertion failed.";
    }
}
function AssertNumArgs(num)
{
    var caller = AssertNumArgs.caller;
    if (caller && caller.arguments.length != num) {
	DumpError("Wrong number of arguments!");
    }
}
function SetCookie(name, value, expires_ms)
{
    var date = new Date();
    var now = date.getTime();
    date.setTime(now + expires_ms);
    document.cookie =
	name + "=" + value + ";path=/;expires=" + date.toGMTString() + "; domain=.mipang.com";
}

function GetCookie(name)
{
    var cookie = String(document.cookie);
    var pos = cookie.indexOf(name + "=");
    if (pos != -1) {
	var end = cookie.indexOf(";", pos);
	return cookie.substring(pos + name.length + 1,
				end == -1 ? cookie.length : end);
    }
    return "";
}

function Now()
{
    return (new Date()).getTime();
}

function GetElement(win, id)
{
    return win.document.getElementById(id);
}

function SetInnerHTML(win, id, html)
{
    try {
	GetElement(win, id).innerHTML = html;
    }
    catch(ex) {
	DumpException(ex, "Cannot set inner HTML: " + id);
    }
}
function GetInnerHTML(win, id)
{
    try {
	return GetElement(win, id).innerHTML;
    }
    catch(ex) {
	DumpException(ex, "Cannot get inner HTML: " + id);
	return "";
    }
}
function ClearInnerHTML(win, id)
{
    try {
	GetElement(win, id).innerHTML = "";
    }
    catch(ex) {
	DumpException(ex, "Cannot set inner HTML: " + id);
    }
}
function SetCssStyle(win, id, name, value)
{
    try {
	var elem = GetElement(win, id);
	if (elem) {
	    elem.style[name] = value;
	}
    }
    catch(ex) {
	DumpException(ex);
    }
}
function ShowElement(el, show)
{
    el.style.display = show ? "" : "none";
}

function ShowBlockElement(el, show)
{
    el.style.display = show ? "block" : "none";
}

function SetButtonText(button, text)
{
    button.childNodes[0].nodeValue = text;
}

function AppendNewElement(win, parent, tag)
{
    var e = win.document.createElement(tag);
    parent.appendChild(e);
    return e;
}
function InsertNewElement(win, parent, tag)
{
    var e = win.document.createElement(tag);
    if(parent.hasChildNodes())
	parent.insertBefore(e,parent.firstChild);
    else
	parent.appendChild(e);
    return e;
}

function CreateDIV(win, id)
{
    var div = GetElement(win, id);
    if (!div) {
	var div = AppendNewElement(win, win.document.body, "div");
	div.id = id;
    }
    return div;
}
function CreateDIV2(win, id)
{
    var div = GetElement(win, id);
    if (!div) {
	var div = InsertNewElement(win, win.document.body, "div");
	div.id = id;
    }
    return div;
}

function CreateIFRAME(win, id, url)
{
    var iframe = GetElement(win, id);
    if (!iframe) {
	var div = AppendNewElement(win, win.document.body, "div");
	div.innerHTML =
	    "<iframe id=" + id + " name=" + id + " src=" + url +
	    "></iframe>";
	iframe = GetElement(win, id);
    }
    return iframe;
}

function HasClass(el, cl)
{
    if (el.className == null) {
	return false;
    }
    var classes = el.className.split(" ");
    for (var i = 0; i < classes.length; i++) {
	if (classes[i] == cl) {
	    return true;
	}
    }
    return false;
}

function AddClass(el, cl)
{
    if (HasClass(el, cl)) {
	return;
    }
    el.className += " " + cl;
}
function RemoveClass(el, cl)
{
    if (el.className == null) {
	return;
    }
    var classes = el.className.split(" ");
    var result =[];
    for (var i = 0; i < classes.length; i++) {
	if (classes[i] != cl) {
	    result[result.length] = classes[i];
	}
    }
    el.className = result.join(" ");
}


function GetPageOffsetLeft(el)
{
    var x = el.offsetLeft;
    if (el.offsetParent != null) {
	x += GetPageOffsetLeft(el.offsetParent);
    }
    return x;
}

function GetPageOffsetTop(el)
{
    var y = el.offsetTop;
    if (el.offsetParent != null) {
	y += GetPageOffsetTop(el.offsetParent);
    }
    return y;
}

function GetPageOffset(el)
{
    var x = el.offsetLeft;
    var y = el.offsetTop;
    if (el.offsetParent != null) {
	var pos = GetPageOffset(el.offsetParent);
	x += pos.x;
	y += pos.y;
    }
    return {
  x:x, y:y};
}
function GetPageOffsetRight(el)
{
    return GetPageOffsetLeft(el) + el.offsetWidth;
}

function GetPageOffsetBottom(el)
{
    return GetPageOffsetTop(el) + el.offsetHeight;
}

function GetScrollTop(win)
{
    var doc = win.document;
    var body = doc.documentElement ? doc.documentElement : doc.body;
    return is_ie ? body.scrollTop : win.pageYOffset;
}
function GetScrollLeft(win)
{
    var doc = win.document;
    var body = doc.documentElement ? doc.documentElement : doc.body;
    return is_ie ? body.scrollLeft : win.pageXOffset;
}

function ScrollTo(win, el, position)
{
    var y = GetPageOffsetTop(el);
    y -= GetWindowHeight(win) * position;
    win.scrollTo(0, y);
}

function ScrollIntoView(win, el, alignment)
{
    var el_top = GetPageOffsetTop(el);
    var el_bottom = el_top + el.offsetHeight;
    var win_top = GetScrollTop(win);
    var win_height = GetWindowHeight(win);
    var win_bottom = win_top + win_height;
    if (el_top < win_top || el_bottom > win_bottom) {
	var scrollto_y;
	if (alignment == 'b') {
	    scrollto_y = el_bottom - win_height + 5;
	} else {
	    if (alignment == 'm') {
		scrollto_y = (el_top + el_bottom) / 2 - win_height / 2;
	    } else {
		scrollto_y = el_top - 5;
	    }
	}
	Debug("Scrolling to " + scrollto_y);
	win.scrollTo(0, scrollto_y);
    }
}

//get window size.
function GetWindowWidth(win)
{
    var doc = win.document;
    var body = doc.documentElement ? doc.documentElement : doc.body;
    return is_ie ? body.clientWidth : win.innerWidth;
}

function GetWindowHeight(win)
{
    var doc = win.document;
    var body = doc.documentElement ? doc.documentElement : doc.body;
    return is_ie ? body.clientHeight : win.innerHeight;
}

function GetAvailScreenWidth()
{
    return screen.availWidth;
}

function GetAvailScreenHeight()
{
    return screen.availHeight;
}

function GetNiceWindowHeight(win)
{
    return Math.floor(0.88 * GetAvailScreenHeight());
}
function GetCenteringLeft(width)
{
    return Math.floor((screen.availWidth - width) / 2);
}

function GetCenteringTop(height)
{
    return Math.floor((screen.availHeight - height) / 2);
}
//open new Window.
function OpenInternalWindow(win, url, name, features)
{
    return OpenExternalWindow(win, U_MakeUnique(url), name, features);
}

function OpenExternalWindow(win, url, name, features)
{
    var newwin = _OpenWindowHelper(top, url, name, features);
    if (!newwin) {
	newwin = _OpenWindowHelper(win, url, name, features);
    }
    if (!newwin) {
	alert
	    ('Grrr! A popup blocker may be preventing Gmail from opening the page. If you have a popup blocker, try disabling it to open the window.');
    } else {
	newwin.focus();
    }
    return newwin;
}

function _OpenWindowHelper(win, url, name, features)
{
    var newwin;
    if (features) {
	newwin = win.open(url, name, features);
    } else {
	if (name) {
	    newwin = win.open(url, name);
	} else {
	    newwin = win.open(url);
	}
    }
    return newwin;
}

function CloseWindow(win)
{
    win.top.close();
}

function Popup(win, url, name, width, height, do_center)
{
    if (!height) {
	height = Math.floor(GetWindowHeight(win.top) * 0.88);
    }
    if (!width) {
	width = Math.min(GetAvailScreenWidth(), height);
    }
    var features =
	"resizable=yes,scrollbars=yes,width=" + width + ",height=" +
	height;
    if (do_center) {
	features +=
	    ",left=" + GetCenteringLeft(width) + "," + "top=" +
	    GetCenteringTop(height);
    }
    return OpenInternalWindow(win, url, name, features);
}




//string stuff
function HtmlEscape(str){
	if(typeof str != 'string')
		str = String(str);
    return str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
}
function QuoteEscape(str){
    return HtmlEscape(str);//.replace(/\"/g,"&quot;");
}
function CollapseWhitespace(str){
    return str.replace(/\s+/g," ").replace(/^ /,"").replace(/ $/,"");
}
function StripNewlines(str){
    return str.replace(/[\r\n]/g," ");
}
function NormalizeSpaces(str){
    return str.replace(/[ \t]+/g," ").replace(/\xa0/g," ");
}

function StripHtmlTags(str){
	return str.replace(/<[^><]*(>|$)/g," ").replace(/(&[^&]{2,5}(;|$))+/g," ").replace(/^\s+/,"");
}

function StrSafeInline(str){
	return HtmlEscape(str).replace(/\\/g,/*'&#92;'*/'\\\\').replace(/(\r\n?|\n)/g,'\\n').replace(/\'/g,'\\\'');
}

function UrlEncode(str){
    return encodeURIComponent(str);
}
function Trim(str){
    return str.replace(/^\s+/,"").replace(/\s+$/,"");
}
function EndsWith(str, suffix){
    return (str.lastIndexOf(suffix)==(str.length-suffix.length));
}
function IsEmpty(str)
{
    return CollapseWhitespace(str) == "";
}

function IsLetterOrDigit(ch)
{
    return ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z")
	    || (ch >= '0' && ch <= '9'));
}

function IsSpace(ch)
{
    return (" \t\r\n".indexOf(ch) >= 0);
}

var eol_re_=/\r\n?/g;
function ConvertEOLToLF(str)
{
    return str.replace(eol_re_, "\n");
}

function HtmlEscapeInsertWbrs(str, n, chars_to_break_after,
			      chars_to_break_before)
{
    AssertNumArgs(4);
	if(typeof str != 'string')
		str = String(str);
	
    var out = '';
    var strpos = 0;
    var spc = 0;
    for (var i = 1; i < str.length; ++i) {
	var prev_char = str.charAt(i - 1);
	var next_char = str.charAt(i);
	if (IsSpace(next_char)) {
	    spc = i;
	} else {
	    if (i - spc == n
		|| chars_to_break_after.indexOf(prev_char) != -1
		|| chars_to_break_before.indexOf(next_char) != -1) {
		out += HtmlEscape(str.substring(strpos, i)) + '<wbr>';
		strpos = i;
		spc = i;
	    }
	}
    }
    out += HtmlEscape(str.substr(strpos));
    return out;
}

function GetCursorPos(win, textfield)
{
    if (IsDefined(textfield.selectionEnd)) {
	return textfield.selectionEnd;
    } else {
	if (win.document.selection && win.document.selection.createRange) {
	    var tr = win.document.selection.createRange();
	    var tr2 = tr.duplicate();
	    tr2.moveToElementText(textfield);
	    tr2.setEndPoint("EndToStart", tr);
	    var cursor = tr2.text.length;
	    if (cursor > textfield.value.length) {
		return -1;
	    }
	    return cursor;
	} else {
	    Debug("Unable to get cursor position for: " +
		  navigator.userAgent);
	    return textfield.value.length;
	}
    }
}
function SetCursorPos(win, textfield, pos)
{
    if (IsDefined(textfield.selectionEnd)
	&& IsDefined(textfield.selectionStart)) {
	textfield.selectionStart = pos;
	textfield.selectionEnd = pos;
    } else {
	if (win.document.selection && textfield.createTextRange) {
	    var sel = textfield.createTextRange();
	    sel.collapse(true);
	    sel.move("character", pos);
	    sel.select();
	}
    }
}


function Map()
{
}

Map.prototype.get = function(key)
{
    return this[':' + key];
};

Map.prototype.put = function(key, value)
{
    this[':' + key] = value;
};

Map.prototype.remove = function(key)
{
    delete this[':' + key];
};
function Set(array)
{
    if (array) {
	for (var i = 0; i < array.length; i++) {
	    this.add(array[i]);
	}
    }
}

Set.prototype.add = function(entry)
{
    this[':' + entry] = 1;
};

Set.prototype.remove = function(entry)
{
    delete this[':' + entry];
};

Set.prototype.contains = function(entry)
{
    return (this[':' + entry] == 1);
};
function FindInArray(array, x)
{
    for (var i = 0; i < array.length; i++) {
	if (array[i] == x) {
	    return i;
	}
    }
    return -1;
}

function InsertArray(array, x)
{
    if (FindInArray(array, x) == -1) {
	array[array.length] = x;
    }
}
function DeleteArrayElement(array, x)
{
    var i = 0;
    while (i < array.length && array[i] != x)
	i++;
    array.splice(i, 1);
}

function CloneObject(x)
{
    if ((typeof x) == "object") {
	var y =[];
	for (var i in x) {
	    y[i] = CloneObject(x[i]);
	}
	return y;
    }
    return x;
}

function PrintArray(array)
{
    AssertEquals(array.length, PrintArray.arguments.length * 2 - 1);
    var idx = 1;
    for (var i = 1; i < PrintArray.arguments.length; i++) {
	array[idx] = PrintArray.arguments[i];
	idx += 2;
    }
    return array.join("");
}


function ImageHtml(url, attributes)
{
    return "<img " + attributes + " src=" + url + ">";
}
function FormatJSLink(desc, js, classname)
{
    return '<span class="' + classname + '" onclick="' + js + '">' + desc +
	'</span>';
}

function FormatIDLink(desc, id, underline)
{
    return "<span class=" + (underline ? "lk" : "l") + ' id="' + id +
	'">' + desc + "</span>";
}

function FormatURLLink(desc, url, extra)
{
    return '<a href="' + url + '" class=' + "lk" +
	' onclick="return top.MPLINK(window,this,event)" ' +
	(extra ? extra : '') + '>' + desc + "</a>";
}

function MakeId3(idprefix, m, n)
{
    return idprefix + m + "_" + n;
}

function IsDefined(value)
{
    return (typeof value) != 'undefined';
}


function XmlHttpCreate()
{
    var xmlhttp = null;
    if (is_ie) {
	var control = (is_ie5) ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP";
	try {
	    xmlhttp = new ActiveXObject(control);
	}
	catch(e) {
	    DumpException(e);
	    alert
		("You need to enable active scripting and activeX controls.");
	}
    } else {
	xmlhttp = new XMLHttpRequest();
	if (!xmlhttp) {
	    alert("XMLHttpRequest is not supported on this browser.");
	}
    }
    return xmlhttp;
}

function XmlHttpSend(xmlhttp, data)
{
    try {
	xmlhttp.send(data);
    }
    catch(e) {
	DumpException(e);
	if (e.number == -2146697208.000000) {
	    alert
		("Please make sure the 'Languages..' setting for your Internet Explorer is not empty.");
	}
    }
}
function XmlHttpGET(xmlhttp, url, handler,noUniqUrl)
{
    /**AssertNumArgs(3);**/

    if(!noUniqUrl)
	url = U_MakeUnique(url);

    Debug("Server request: GET " + url);
    xmlhttp.onreadystatechange = handler;
    xmlhttp.open("GET", url, true);
    XmlHttpSend(xmlhttp, null);
}

function XmlHttpPOST(xmlhttp, url, data, handler)
{
    AssertNumArgs(4);
    Debug("Server request: POST " + url);
    xmlhttp.onreadystatechange = handler;
	//alert(url);
    xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    XmlHttpSend(xmlhttp, data);
}



//URL opt...
function U_Param(key, value)
{
    return "&" + key + "=" + UrlEncode(value);
}

function U_FirstParam(key, value)
{
    return "?" + key + "=" + UrlEncode(value);
}

function U_AppendParam(url, key, value)
{
    if (url.indexOf('?') < 0) {
	return url + U_FirstParam(key, value);
    } else {
	return url + U_Param(key, value);
    }
}function U_MakeUnique(url)
{
    if (url.indexOf('?') < 0) {
	return url;
    }
    var rand_str =
	js_version + Math.round(Math.random() * 2147483648.000000);
    return U_AppendParam(url, "zx", rand_str);
}


/////DEBUG.........
function DB_WriteDebugMsg()
{
}
function Debug(str)
{
    DB_WriteDebugMsg(str, 0);
}

function DumpError(str)
{
    try {
	throw str;
    }
    catch(e) {
	DumpException(e);
    }
}
function DumpException(e, msg)
{
    var error =
	"Javascript exception: " + (msg ? msg : "") + " " + e + "\n";
    for (var i in e) {
	//error += i + ": " + e[i] + " | ";
    }
	error+='\n';
    error += DB_GetStackTrace(DumpException.caller);
    alert(error);
 /*   DB_WriteDebugMsg(error, 1);
    DB_SendJSReport(error);
	*/
}

function DumpObj(obj,prefix)
{
    prefix = prefix || '';
    var s = '';
    for(var x in obj){
	if(typeof obj[x] == 'object'){
	    s += prefix + x + ' = \n' + DumpObj(obj[x],prefix+'... ');
	}else
	    s += prefix + x + ' = '+obj[x] + '\n';
    }
    return s;
}


function DB_GetFunctionName(fn){
    //return String(fn).substr(0,200);
    var m=/function (\w+)/.exec(String(fn));
    if(m){return m[1];
    }
    return "";
}
function DB_GetStackTrace(fn)
{
    try {
	if (is_nav) {
	    return Error().stack;
	}
	if (!fn) {
	    return "";
	}
	var x = "\- " + DB_GetFunctionName(fn) + "(";
	for (var i = 0; i < fn.arguments.length; i++) {
	    if (i > 0) {
		x += ", ";
	    }
	    var arg = String(fn.arguments[i]);
	    if (arg.length > 40) {
		arg = arg.substr(0, 40) + "...";
	    }
	    x += arg;
	}
	x += ")\n";
	x += DB_GetStackTrace(fn.caller);
	return x;
    }
    catch(ex) {
	return "[Cannot get stack trace]: " + ex + "\n";
    }
}




function getEventSrc(e){
	if (e){ return e.target; }
	if (window.event){ return window.event.srcElement; }
	return null;
}

function EV_GetEventTarget(e)
{
    var src = e.srcElement ? e.srcElement : e.target;
    if (is_safari && src && src.nodeType == 3) {
	src = src.parentNode;
    }
    return src;
}


function EV_GetKeyCode(e)
{
    return is_ie ? e.keyCode : e.which;
}

function EV_GetKeyChar(e)
{
    var keycode = EV_GetKeyCode(e);
    if (is_ie && e.ctrlKey) {
	keycode += 64;
    }
    return String.fromCharCode(keycode).toLowerCase();
}

function EV_GetMouseXPos(win, e)
{
    var doc = win.document;
    var body = doc.documentElement ? doc.documentElement : doc.body;
    return is_ie ? (e.x + body.scrollLeft) : e.pageX;
}
function EV_GetMouseYPos(win, e)
{
    var doc = win.document;
    var body = doc.documentElement ? doc.documentElement : doc.body;
    return is_ie ? (e.y + body.scrollTop) : e.pageY;
}



var EV_Attach=function(o,a,f,i){
    i = !(!i);
    if(o.addEventListener){
	o.addEventListener(a,f,i);
    }else if(o.attachEvent){
	o.attachEvent("on"+a,f);
    }
};

var EV_Detach=function(o,a,f,i)
{
    i = !(!i);
    if(o.removeEventListener){
	o.removeEventListener(a,f,i);
    }else if(o.detachEvent){
	o.detachEvent("on"+a,f);
    }
};


var _ge = function(id) {
    return GetElement(window,id);
};


var _pi = function(str) {
	return parseInt(str);
};


var _re_email = /^[0-9a-zA-Z]+(\.?[0-9a-zA-Z_\-]+)*@([0-9a-zA-Z]+[0-9a-zA-Z_\-]*\.?)*[0-9a-zA-Z]+[0-9a-zA-Z_\-]*$/ ;



///From Flick js....


// EXTEND BUILT IN OBJECTS

if (!Array.prototype.push) {
	Array.prototype.push = function() {
		var i = 0, b = this.length, a = arguments;
		for (i; i<a.length; i++) this[b+i] = a[i];
		return this.length;
	}
}

if (!Array.prototype.pop) {
	Array.prototype.pop = function() {
		var  b = this[this.length-1];
		this.length--;
		return b;
	}
}

if(!Array.prototype.merge){
    /** to be fixed
    Array.prototype.merge = function(){
	var i = 0, b = this.length, a = arguments;
	for (i; i<a.length; i++) ;
	return this;
    };
    **/
}

if(!String.prototype.chop){
	String.prototype.chop = function() {
		return this;
	}
}

function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}

if(!String.prototype.nl2br){
	String.prototype.nl2br = function() {
		return this.split('\n').join('<br \/>\n');
	}
}
if(!String.prototype.replaceFast){
	String.prototype.replaceFast = function(find,replace) {
		return this.split(find).join(replace);
	}
}
if(!String.prototype.escapeForXML){
	String.prototype.escapeForXML = function() {
		return this.replace('&', '&amp;').replace('"', '&quot;').replace('<', '&lt;').replace('>', '&gt;');
	}
}
if(!String.prototype.escapeForDisplay){
	String.prototype.escapeForDisplay = function() {
		return this.replace('<', '&lt;');
	}
}
if(!String.prototype.truncate_with_ellipses){
	String.prototype.truncate_with_ellipses = function(chars_allowed) {
		var t = this;
		if (t.length > chars_allowed-3) {
			t = t.substr(0, chars_allowed-3)+'...'
		}
		return t;
	}
}

if(!String.prototype.UrlEncode){
	String.prototype.UrlEncode = function() {
   	 return encodeURIComponent(this);
	}
}




function okForXMLHTTPREQUESTandResponseXML(){
	if (global_fakeOperaXMLHttpRequestSupport) return false; // this is set in xmlhtttprequest.js
	return okForXMLHTTPREQUEST();
}

function okForXMLHTTPREQUEST(){
	if (!window.XMLHttpRequest) return false;
	if (navigator.appVersion.toLowerCase().indexOf("mac") > 0 && navigator.userAgent.indexOf('MSIE') > 0 && navigator.userAgent.indexOf('Opera') == -1) return false;
	return true;
}

function escape_utf8(data) {

	if (data == '' || data == null){
		return '';
	}
	data = data.toString();
	var buffer = '';
	for(var i=0; i<data.length; i++){
		var c = data.charCodeAt(i);
		var bs = new Array();

		if (c > 0x10000){
			// 4 bytes
			bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
			bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
			bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
			bs[3] = 0x80 | (c & 0x3F);

		}else if (c > 0x800){
			// 3 bytes
			bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
			bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
			bs[2] = 0x80 | (c & 0x3F);

		}else if (c > 0x80){
			// 2 bytes
			bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
			bs[1] = 0x80 | (c & 0x3F);

		}else{
			// 1 byte
			bs[0] = c;
		}

		for(var j=0; j<bs.length; j++){
			var b = bs[j];
			var hex = nibble_to_hex((b & 0xF0) >>> 4) + nibble_to_hex(b & 0x0F);
			buffer += '%'+hex;
		}
	}

	return buffer;
}

function nibble_to_hex(nibble){
	var chars = '0123456789ABCDEF';
	return chars.charAt(nibble);
}




// findPosX & findPosY courtesy PPK
// http://www.quirksmode.org/js/findpos.html
function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) curtop += obj.y;
	return curtop;
}

 document.getElementsByClass = function (needle, tagName) {
 	if (!tagName) tagName = '*';
	var my_array = document.getElementsByTagName(tagName);
	var retvalue = new Array();
	var i;	 
	var j;

	for (i = 0, j = 0; i < my_array.length; i++) { 	 
		var c = " " + my_array[i].className + " "; 	 
		if (c.indexOf(" " + needle + " ") != -1) retvalue[j++] = my_array[i]; 	 
   }	
   return retvalue;
}



if (!Array.prototype.push) {
	Array.prototype.push = function() {
		var i = 0, b = this.length, a = arguments;
		for (i; i<a.length; i++) this[b+i] = a[i];
		return this.length;
	}
}

if (!Array.prototype.pop) {
	Array.prototype.pop = function() {
		var  b = this[this.length-1];
		this.length--;
		return b;
	}
}


function setCookie(name, value, days) {
	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=/';
}

function getCookie(name) {
	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);
	}
	return null;
}

function deleteCookie(name) {
	SetCookie(name, '', -1);
}

set_rgb = function(prop, r, g, b) {
	this.style[prop] = 'rgb('+r+', '+g+', '+b+')';
}

set_color_rgb = function(r, g, b) {
	set_rgb.call(this, 'color', r, g, b);
}










///////////////////
// my funcs....
////////////////////////////


function isLeapYear(year)
{
    var d = new Date(year,2,1,0,0,0,0);
    d.setTime(d.getTime() - 100);
    return d.getDate() == 29;
}

function htmlencode(str){
	var s = HtmlEscape(str);
	s = s.replace(/  /g,"&nbsp; ");
	s = s.replace(/\t/g,"&nbsp; &nbsp; &nbsp; &nbsp; ");
	s = s.replace(/\n/g,"<br/>");
	return s;
}

function ResizeTextarea(a,row){
    if(!a){return}
    if(!row)
	row=5;
    var b=a.value.split("\n");
    var c=is_ie?1:0;
    c+=b.length;
    var d=a.cols;
    if(d<=20){d=40}
    for(var e=0;e<b.length;e++){
	if(b[e].length>=d){
	    c+=Math.ceil(b[e].length/d)
	}
    }
    c=Math.max(c,row);
    if(c!=a.rows){
	a.rows=c;
    }
}











function getFirstNodeValue(el,tagName)
{
	var node = el.getElementsByTagName(tagName)[0];
	return getNodeValue(node);
}

function getNodeValue(node)
{
	if(node && node.hasChildNodes()){
		//return node.firstChild.nodeValue;
		var s="" 
		//Mozilla has many textnodes with a size of 4096 chars each instead of one large one.
		//They all need to be concatenated.
		for(var j=0;j<node.childNodes.length;j++){
			s+=new String(node.childNodes.item(j).nodeValue);
		}
		return s;	
	}else
		return "";
}

function getParentNodeByTagName(e,tag,minDeep,maxDeep)
{
	try{
	if(!maxDeep)
		maxDeep=50;
	if(!minDeep)
		minDeep=0;
	if(minDeep>=maxDeep)
		return null;
	var i=0;
	while( (e=e.parentNode) && (e.tagName.toLowerCase() != tag.toLowerCase() || minDeep>i ) && i<maxDeep){		
		i++;
	}
	if(e && i < maxDeep)
		return e;
	else 
		return null;	
	}catch(e){return null;}
}

function getParentNodeByName(e,name,minDeep,maxDeep)
{
	try{
	if(!maxDeep)
		maxDeep=50;
	if(!minDeep)
		minDeep=0;
	if(minDeep>=maxDeep)
		return null;
	var i=0;
	while( (e=e.parentNode) && i<maxDeep){		
		if(e.getAttribute('name') && String(e.getAttribute('name')) == name ){
			if(i>=minDeep){
				break;
			}
		}
		i++;
	}
	if(e && i < maxDeep)
		return e;
	else 
		return null;	
	}catch(e){return null;}
}


/*disable the Enter Key event ,just for IE.*/
function form_disable_EnterKey(Event,f)
{
try{	
	var fe = _ge(f);
	var es = fe.getElementsByTagName('input');
	for(var i=0;i<es.length;i++){
		var e=es[i];
		if(e.type=='text'){
			e.onkeydown = function(){
				if(!Event)
					Event = window.event;
				if(Event.keyCode==13) Event.returnValue=false;
			};
		}
	}
}catch(e){}
}


function CopyArray(arr)
{
	var n=[];
	if(!arr || !arr.length)
		return n;
	for(var i=0;i<arr.length;i++){
		n[i] = arr[i];		
	}	
	return n;
}





/*////////////////// XmlHttpRequest /////////////////////*/

// IE support
if (window.ActiveXObject && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');
  };
}
// Gecko support
/* ;-) */
// Opera support
global_fakeOperaXMLHttpRequestSupport = false;

// ActiveXObject emulation
if (!window.ActiveXObject && window.XMLHttpRequest) {
  window.ActiveXObject = function(type) {
    switch (type.toLowerCase()) {
      case 'microsoft.xmlhttp':
      case 'msxml2.xmlhttp':
        return new XMLHttpRequest();
    }
    return null;
  };
}



function SendReq4XML(url,data,callback,cb_argsObj,debug)
{
	var xmlhttp = XmlHttpCreate();
	
    var handler =
	function(){
        try {
            if (4 == xmlhttp.readyState && 200 == xmlhttp.status) {
				if(debug) 
					alert('Length:'+xmlhttp.responseText.length+"\n"+xmlhttp.responseText);
				//alert(xmlhttp.responseText.length);
				if(cb_argsObj)
					callback(xmlhttp.responseXML,cb_argsObj);
				else
					callback(xmlhttp.responseXML);
            }
        }
		catch(exx) {
			DumpException(exx);
		}
    };	
	XmlHttpPOST(xmlhttp, url, data, handler);			
}


///////////////////////////
// my funcs....
function XmlHttpGetError(rsXML)
{
	//arg1 is a XML FROMAT result
	try{
		var err = rsXML.documentElement.getElementsByTagName('error')[0];
		if(err){
			var code = getFirstNodeValue(err,'code');
			var desc = getFirstNodeValue(err,'desc');
			var error = new Object();
			error.code=code;
			error.desc=desc;
			return error;
		}
	}catch(e){
		//DumpException(e);
		return null;
	}
	return null;
}


///////////////////////////////////////////////////
/// My APIs... TOBE UPGRADE Later...
///////////////////////////////////////////////////
var MyAPI = {};
MyAPI.callMethod = function(APIMethod, params, listener, CBParams/*callback {args}*/,APIURL, attempts, server,method,cache/* get(method) cache */) {
	if (typeof params != 'object') params = {}; // because we are going to stick a few things in even if no params are passed
	params.method = APIMethod; // see? And this also makes sure a method parameter is not passed
	
	var url = '/service/api';
	if(APIURL) url = APIURL;
	if (server) url = server + url;
	
	var data = 'APIv=0.1';
	
	for (var p in params) {
		if (p=='RESTURL') continue;
		if(p=='RAW_QUERY'){
			data+='&'+params[p];
			continue;
		}
		params[p] = params[p];
		//params_keyA.push(p);
		data+= '&'+p+'='+UrlEncode(params[p]);//escape_utf8(params[p]);
	}

	params.RESTURL = data; // again. we stick this in here because we pass params to the callback, and it might want to see the URL
	
	//alert(data);
	
	var attempts = (attempts == undefined) ? 1 : attempts;
	
	var req = XmlHttpCreate();
	
	if (!req){
		return ;
	}
	
	var callback = function() {
		//alert(req.readyState+'/'+req.status);
		if (4 == req.readyState ){
			if( 200 == req.status ){
				if( typeof MyAPI == 'object') 
				MyAPI.handleResponse(req.responseXML, APIMethod, params, req.responseText, listener,CBParams);
			}else{
				if( 0 || //req.responseText == '' &&
					attempts<2
					) {
					attempts++;
					req.abort();
					MyAPI.callMethod(APIMethod, params, listener, CBParams,APIURL, attempts, server);
				} 			
			}
		}
	};

	if(url.indexOf('/service/proxy/') != 0){

	    // fix vhost
	    if(url.indexOf('/') == 0 && typeof MIPANG != 'undefined' && typeof MIPANG.location !='undefined' ){

		url = MIPANG.location.scheme + '://'+MIPANG.location.main_host + url;

	    }


	    if(typeof MIPANG != 'undefined' && typeof MIPANG.location != 'undefined' && MIPANG.location.main_host != MIPANG.location.current_host){
		url = '/service/proxy/*/'+url;
	    }

	    //alert(url);

	}

	if(method && method=='GET')
	    XmlHttpGET(req,url,callback,cache);
	else
	    XmlHttpPOST(req,url,data,callback);		
};

MyAPI.getCallBackName = function (dotted) {
	return dotted.split('.').join('_')+'_onLoad';
};

MyAPI.handleResponse = function(responseXML, APIMethod, params, responseText, listener,CBParams) {
	var success = {code:0,desc:''};
	
	if (!responseXML) { //OPERA!
		if(responseText.indexOf('stat="ok"') > -1){
			success.code = 0;
			success.desc = '';
		}else{
			success.code = 888;
			success.desc = responseText;
		}
	} else {
		var err = XmlHttpGetError(responseXML);
		if(!err){
			if(responseXML.documentElement && responseXML.documentElement.getAttribute('code') ){
				success.code = responseXML.documentElement.getAttribute('code')*1;
				success.desc = success.code==0?'SUCCESS':responseText;
			}else{
				success.code = 888; // Error Msg.
				success.desc = responseText;
			}
		}
		if(err){
			success = err;
		}
	}
//	success.desc = responseText;
	//writeAPIDebug(responseText);
	if(!listener) return;
	
	listener = (listener) ? listener : this;
	listener[this.getCallBackName(APIMethod)](success, responseXML, responseText, params,CBParams);
};


/** func add **/





/** misc */
if(!window.__handle_uid)
    window.__handle_uid=1000;
function ExportHandle(obj,prefix)
{
    if(!obj) return;
    if(!prefix)
	prefix = 'ObjectHandle';
    obj.handle_str = '__'+prefix+'_'+(new Date()).getTime()+(++window.__handle_uid);
    window[obj.handle_str] = obj;
}

var MP_DOM_onLoad = new Map();
window.__mp_dom_onload_count = (new Date()).getTime();
window.__mp_dom_loaded_done = false;
function onloadRegister2(fn)
{
    if(window.__mp_dom_loaded_done){
	try{
	    fn();
	}catch(ex){}
	return;
    }
    var fkey = '_dom_onload_fn_'+(window.__mp_dom_onload_count++);
    MP_DOM_onLoad.put(fkey,fn);
}
var onloadRegisterHandler = onloadRegister2;
onloadRegister2(function(){ window.__mp_dom_loaded_done = true; });

/** for blog thumb image detect **/
var __blog_thumb_ban_url_set = new Set();
__blog_thumb_ban_url_set.add('http://imgcache.qq.com/qzone_v4/b.gif');
var __blog_thumb_ban_url_list = [
				 'imgcache.qq.com/qzone_v4/b.gif',
				 '/qzone_v4/b.gif',
				 'imgcache.qq.com/ac/b.gif',
				 'imgcache.qq.com/qzone/em/'
				 ];
function __blog_thumb_ban_url_test(url)
{
    var list = __blog_thumb_ban_url_list;
    for(var i = 0;i < list.length; i++){
	if(String(url).indexOf(list[i]) != -1)
	    return true;
    }
    return false;
    /**
       return (__blog_thumb_ban_url_list.contains(url));
    **/
}

try{ /**client timestamp*/
SetCookie('_tsc',new Date().getTime(),3600*24*365*1000);
}catch(ex){}



/** simple tpl render **/

/** data:{item:string}**/
function simple_tpl_render(tpl,data,dropempty)
{
    return tpl.replace(/\[%([^%]+)%\]/g,
		function(a,b){
		    if( b in data){
			return data[b];
		    }
		    if(dropempty) return '';

		    return a;
		}
	);
}

/** css dynamic append **/
var __mp_dcss_pool = new Map();
function MP_appendCssText(index,cssText){
    
    var st = document.createElement('style');
    st.setAttribute('type','text/css');
    
    onloadRegisterHandler(function(){
	    document.getElementsByTagName('head')[0].appendChild(st);

	    var ibox = __mp_dcss_pool.get(index);
	    
	    var oCss = '';
	    if(ibox){
		oCss = ibox.innerHTML;
		
		document.getElementsByTagName('head')[0].removeChild(ibox);
	    }
    
	    if(st.styleSheet){
		st.styleSheet.cssText = oCss + cssText;
	    }else{
		st.appendChild(document.createTextNode(oCss + cssText));
	    }
	    
    
	    ibox = st;
	    __mp_dcss_pool.put(index,ibox);

	});

}

function MP_SetCssText(index,cssText){
    
    var st = document.createElement('style');
    st.setAttribute('type','text/css');

    cssText = cssText ? cssText : '';
    
    onloadRegisterHandler(function(){
	    document.getElementsByTagName('head')[0].appendChild(st);

	    var ibox = __mp_dcss_pool.get(index);
	    
	    var oCss = '';
	    if(ibox){
		document.getElementsByTagName('head')[0].removeChild(ibox);
	    }
    
	    if(st.styleSheet){
		st.styleSheet.cssText = oCss + cssText;
	    }else{
		st.appendChild(document.createTextNode(oCss + cssText));
	    }
	    
    
	    ibox = st;
	    __mp_dcss_pool.put(index,ibox);

	});

}


/** regexp **/
function regexp_escape(str)
{
    return str.replace(/([\^*+\-\$\\\{\}\(\)\[\]\#?\.])/g,"\\$1")
}



/* mipang namespace */
if(typeof(MIPANG) == 'undefined'){
    var MIPANG = {};
}

/* --- page function --- */


function __PPUW(url)
{
    return Popup(window, url, 'PhotoUploadWindow_'+(new Date()).getTime(), 600, GetAvailScreenHeight(window)-40);
}
/* browser check */
MIPANG._bc=function()
{
    try{
	var agt = navigator.userAgent.toLowerCase();
	var is_op = (agt.indexOf("opera") != -1);
	var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op;
	var is_ie5 = (agt.indexOf("msie 5") != -1) && document.all && !is_op;
	if((is_ie && is_ie5)) document.write('<div style="color:#ffffff;background-color:red;">很抱歉，你正在使用的IE浏览器版本较低。目前我们仅保证在IE6/7和<a href="http://www.mozilla.com/firefox/" style="color:#ffffff;font-weight:bold;">FireFox</a>下工作正常。</div>');
    }catch(e){}
};



/* fireEvent my test version */
function MP_fireEvent(element,event){
    if(document.createEvent){
	// dispatch for firefox + others
	var evt = document.createEvent("HTMLEvents");
	evt.initEvent(event, true, true ); // event type,bubbling,cancelable
	return !element.dispatchEvent(evt);
    }
    else{
	// dispatch for IE
	var evt = document.createEventObject();
	return element.fireEvent('on'+event,evt);
    }
}


/* mipang cps client */

onloadRegisterHandler(function(){
    
    try{
	
	/* 
	 * CPS params:
	 * @_mipang_cps_id
	 * @_mipang_cps_aid
	 */
	
	var uri = URI();
	var q = uri.getQueryData();

	if(typeof q._mipang_cps_id == 'undefined'){ 
	    _cps_trace_seo();
	    return;
	}
	
	var cpsid = q._mipang_cps_id;
	
	var cpsaid = typeof q._mipang_cps_aid  == 'undefined' ? 0 : q._mipang_cps_aid;
	
	var nq = q;

	for(var x in nq){
	    if(x.match(/^_mipang_cps_/))
		delete nq[x];
	}

	uri.setQueryData(nq);

	var from_url = document.referrer ? document.referrer : '';

	var uri2 = new URI('http://cps.mipang.com/trace');

	uri2.setQueryData({
		url:uri._toString(),
		    from_url:from_url,
		    cpsid:cpsid,
		    aid:cpsaid,
		    rdr:'image',
		    __ut:(new Date()).getTime()
		    });


	var x = document.createElement('div');
	x.setAttribute('style','');
	x.style['height'] = '0';
	x.style['overflow'] = 'hidden';
	x.innerHTML = '<img src="'+uri2._toString()+'"/>';
	document.body.appendChild(x);
	/**
	(new Image()).src = uri2._toString();
	**/
    }catch(ex){  }
});


/* trace seo source*/
function _cps_trace_seo(){

    var cookie_cps = GetCookie('__mcps');

    //alert(cookie_cps);
    if(cookie_cps) return;
    //return;
    var referer = document.referrer;
    //alert(typeof referer);
    var r=String(referer);
    //http://www.google.cn/search?hl=zh-CN&newwindow=1&q=%E6%99%AE%E9%99%80%E5%B1%B1%E6%97%85%E6%B8%B8&aq=f&aqi=g10&aql=&oq=
    //http://www.google.com/search?hl=en&source=hp&q=%E6%99%AE%E9%99%80%E5%B1%B1%E6%97%85%E6%B8%B8&aq=f&aqi=&aql=&oq=
    //http://www.google.com.hk/search?hl=en&source=hp&q=%E6%99%AE%E9%99%80%E5%B1%B1%E6%97%85%E6%B8%B8&aq=f&aqi=&aql=&oq=
    //http://www.baidu.com/s?wd=%C6%D5%CD%D3%C9%BD%C2%C3%D3%CE
    //http://www.baidu.com/s?tn=site888_2_pg&lm=-1&word=%B6%AB%D6%C1%CC%EC%C6%F8%D4%A4%B1%A8?14ca450f4318ae4884ec819e9addba76=4680726efac54593a1363482f6ad087b
    //http://www.baidu.com/s?tn=site888_2_pg&bs=%C3%F7%B9%E2%CC%EC%C6%F8%D4%A4%B1%A8&f=8&wd=%C3%F7%B9%E2%CC%EC%C6%F8%D4%A4%B1%A8%C3%D7%C5%D6%CD%F8
    //http://www.baidu.com/baidu?tn=fishdesk_pg&ct=134217728&word=%B9%B2%C7%E0%B3%C7+%CC%EC%C6%F8


    var cps_id = 0;

    // google
    if(
       (
	r.match(/^https?:\/\/[^\.]+\.google\.[a-z]{2,2}\/search/)
	|| r.match(/^https?:\/\/[^\.]+\.google\.com\/search/)
	|| r.match(/^https?:\/\/[^\.]+\.google\.com\.[a-z]{2,2}\/search/)
	)
       &&
       r.match(/[\?&]q=/)
       ){
	
	//alert('Google');
	cps_id = 23;
    }else if(
	     (
	      r.match(/^http:\/\/www\.baidu\.com\/s\?/)
	      || r.match(/^http:\/\/www\.baidu\.com\/baidu\?/)
	      )
	     && r.match(/[\?&](word|wd)=/)
	     ){
	//alert('Baidu');
	cps_id = 24;
    }
    
    if(!cps_id) return;
    //alert(r);

    //alert(cps_id);

    var uri = new URI();
    var uri2 = new URI('http://cps.mipang.com/trace');

    uri2.setQueryData({
	    url:uri._toString(),
		from_url:r,
		cpsid:cps_id,
		aid:0,
		rdr:'image',
		__ut:(new Date()).getTime()
		});


    var x = document.createElement('div');
    x.setAttribute('style','');
    x.style['height'] = '0';
    x.style['overflow'] = 'hidden';
    x.innerHTML = '<img src="'+uri2._toString()+'"/>';
    document.body.appendChild(x);
    /**
       (new Image()).src = uri2._toString();
    **/
    
}