/// <reference name="MicrosoftAjax.js" />
/// <reference path="jQuery/jquery-1.2.6.min.js" />

// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
    	window.onload = func;
	} 
	else 
	{
		window.onload = function()
		{
			oldonload();
			func();
		};
	}
}

/* ===============================================
 * ================ COMMON =======================
 * Some common functions for the basic JavaScript objects
 *
 * ===============================================
 */

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/, "");
};

// Define methods for the Array data structure.
Array.prototype.indexOf = function(item, start) 
{ 
  var i;
	for (i = (start || 0); i < this.length; i++) 
	{ 
		if (this[i] == item) 
		{ 
			return i; 
		} 
	} 
	return -1; 
};

Array.prototype.remove = function(obj)
{ 
	var x = [];
	var i; 
	for (i=0; i<this.length; i++)
	{ 
		if (this[i] != obj)
		{ 
			x.push(this[i]); 
		} 
	} 
	return x; 
};

Array.prototype.replace = function(obj1, obj2)
{ 
	var x = [];
	var len = this.length;
	var i;
	for (i=0; i<len; i++)
	{ 
		if (this[i] == obj1)
		{ 
			x.push(obj2); 
		} 
		else
		{ 
			x.push(this[i]); 
		} 
	} 
	return x; 
};


/* ===============================================
 * ============= GET ELEMENTS ====================
 * Methods to help retrieve elements from the DOM.
 *
 * ===============================================
 */

/*
 * Gets all the Elements by given Class Name. 
 * 
 * @param string searchClass - Name of the css class to look for.
 * @param object node - (optional) The node you want to start from. Defaults to 'document' if none is specified. 
 * @param string tagName - (optional) Limit  results by adding a tagName. Defaults to '*' if none is specified.
 * 
 * @returns array - Returns an array containing all the nodes given by the specified className.
 */ 
function getElementsByClass(searchClass, node, tagName)
{
	var	classElements =	[];
	if (node === null)
	{
    node = document;
  }
	if (tagName ===	null) 
	{
    tagName	= '*';
  }
	
	var	els	= node.getElementsByTagName(tagName);
	var	elsLen = els.length;
	
	var i,j;
	for	(i = 0,	j =	0; i < elsLen; i++)
	{
		if (hasClass(els[i], searchClass))
		{
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

/*
 * Get the element from the DOM Tree. If the given parameter (e) is a string, 
 * it is assumed to be the element's ID, and that element will be retrieved, else 
 * the given parameter is returned. 
 * 
 * @param string/element e - the element ID / element to be retrieved from the DOM tree. 
 * 
 * @returns element
 */
function getElement(e)
{
	if (typeof e ==	'string')
	{
		return document.getElementById(e);
	}
	else
	{
		return e;
  }
}

/* ===============================================
 * ================ STYLING ======================
 * Methods for manipulating an element's styles (CSS).
 *
 * ===============================================
 */

function getClasses(element)
{
	return element.className.trim().split(/\s+/);
}

function hasClass(element, className)
{
	return getClasses(element).indexOf(className) != -1;
}

function addClass(element, className)
{
    var classes = getClasses(element);
    
    if (classes.indexOf(className) == -1)
    {
        classes.push(className);
        element.className = classes.join(' ');
    }
}

function removeClass(element, className)
{
    var classes = getClasses(element);
    var index = classes.indexOf(className);
    
    if (index != -1)
    {
        classes.splice(index, 1);
        element.className = classes.join(' ');
    }
}

function showElement(element)
{ 
	element = getElement(element);
	
	if (element) // if we don't find the element, don't try to access it's properties.
	{
		element.style.display = "";
	}
}

function hideElement(element)
{
	element = getElement(element);
        
	if (element)
	{
		element.style.display = "none";
	}
}

/*
	Prototype for a javascript BlogInfo object 
	that provides information to client scripts 
	much as a server version does.
*/
function blogInfo(virtualRoot, virtualBlogRoot,blogId,subfolder)
{

	/*
	Returns the virtual root for the entire website.
	*/
	function getVirtualRoot()
	{
		return this.virtualRoot;
	}
	
	/*
	Gets the virtual root for the specific blog.
	*/
	function getVirtualBlogRoot()
	{
		return this.virtualBlogRoot;
    }

    function getCurrentBlogId() {
        return this.blogId;
    };

    function getSubfolder() {
        return this.subfolder;
    }
	/*
	Returns the virtual root to the default "scripts" directory 
	*/
	function getScriptsVirtualRoot()
	{
		return this.virtualRoot + "Scripts/";
	}
	
	/*
	Returns the virtual root to the default "scripts" directory 
	*/
	function getImagesVirtualRoot()
	{
		return this.virtualRoot + "Images/";
	}

	this.virtualRoot = virtualRoot;
	this.virtualBlogRoot = virtualBlogRoot;
	this.blogId = blogId;
	this.subfolder = subfolder;
	
	this.getVirtualRoot = getVirtualRoot;
	this.getVirtualBlogRoot = getVirtualBlogRoot;
	this.getScriptsVirtualRoot = getScriptsVirtualRoot;
	this.getImagesVirtualRoot = getImagesVirtualRoot;
	this.getCurrentBlogId = getCurrentBlogId;
	this.getSubfolder = getSubfolder;

}

/*  操作提示    */
//  =======================
function popupAlert(title, message, type, isConfirm, callback,args) {
    this._title = title;
    this._message = message;
    this._type = type;
    this._isConfirm = isConfirm;
    this._callback = callback;
    this._args = args;
    this._popupBox = $("#popupAlertContainer");
    this._scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
    this._scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    
    this.callback = this._callback;
    this.commandArgument = this._args;
    
    this.show = buildAlertBox;
    function buildAlertBox() {
        if (this._popupBox.size() <= 0) {
            alert(String.format("{0}\r\n{1}", this._title, this._message));
        } else {
            $("dl.context>dd.title", this._popupBox).html(this._title);
            $("dl.context>dd.title", this._popupBox).removeClass("alert error success");
            $("dl.context>dd.title", this._popupBox).addClass(this._type);
            $("dl.context>dd.info", this._popupBox).html(this._message);
            $("dl.context>dt", this._popupBox).removeClass();
            $("dl.context>dt", this._popupBox).addClass(this._type);
            $("a.canel", this._popupBox).unbind("click");
            if (this._isConfirm == true) {
                $("a.canel", this._popupBox).bind("click", { sender: this }, function(e) { e.data.sender.close(e.data.sender); return false; });
            };
            $("a.yes", this._popupBox).unbind("click");
            if ((this._callback != null) && (typeof this._callback == "function")) {
                $("a.yes", this._popupBox).bind("click", { sender:this,commandArgument:this.commandArgument }, function(e) { e.data.sender.callback(e.data.sender,e.data.commandArgument); return false; });
            } else {
                $("a.yes", this._popupBox).bind("click", { sender: this }, function(e) { e.data.sender.close(e.data.sender); return false; });
            };
            $("p.popupControl>a", this._popupBox).unbind("click");
            $("p.popupControl>a", this._popupBox).bind("click", { sender: this }, function(e) { e.data.sender.close(e.data.sender); return false; });
            var width = $(this._popupBox).width();
            var height = $(this._popupBox).height();
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();
            this._popupBox.css({ left: ((windowWidth - width) / 2 + this._scrollLeft) + "px", top: ((windowHeight - height) / 2 + this._scrollTop) + "px" });
            $(window).unbind("scroll", updatePosition);
            $(window).bind("scroll", { sender: this }, updatePosition);
            this._popupBox.show();
        };
    };

    this.get_popupBox = getPopupBox;
    function getPopupBox() { return this._popupBox; };

    this.move = updatePosition;
    function updatePosition(e) {
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
        var width = $(e.data.sender.get_popupBox()).width();
        var height = $(e.data.sender.get_popupBox()).height();
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        e.data.sender.get_popupBox().css({ left: ((windowWidth - width) / 2 + scrollLeft) + "px", top: ((windowHeight - height) / 2 + scrollTop) + "px" });
    };

    this.close = closeAlertBox;
    function closeAlertBox(e) {
        if (e.get_popupBox().size() > 0) {
            e.get_popupBox().hide();
            $(window).unbind("scroll", updatePosition);
        };
        e = null;
    };

}

/*  即时异步操作提示    */
//  =====================
function displayLoading(sender, isHide) {
    var loadingBox = null;
    if ($(sender).prev(".loading").size() <= 0 && isHide == false) {
        $("<div class=\"loading\"></div>").insertBefore($(sender));
    }
    loadingBox = $(sender).prev(".loading");
    if (isHide == true) {
        loadingBox.hide();
        sender.show();
    } else {
        loadingBox.show();
        sender.hide();
    }
}

function updateFloatHeaderPosition() {
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
//    var width = $("#floatHeader").width();
//    var height = $("#floatHeader").height();
//    var windowWidth = $(window).width();
//    var windowHeight = $(window).height();
    $("#floatHeader").css({ left: (scrollLeft) + "px", top: (scrollTop) + "px" });
}
addLoadEvent(function(e) {
    //$(window).bind("scroll", updateFloatHeaderPosition);
});

function enjooSiteWindow(element) {
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
    var width = $(element).width();
    var height = $(element).height();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    $(element).css({ left: ((windowWidth - width) / 2 + scrollLeft) + "px", top: ((windowHeight - height) / 2 + scrollTop- height/4) + "px" }).show();
}

function enjooSite_Widget(e) {
    this["commandArgument"] = e;
    this["open"] = function(title, contentId, options) {
        var settings = { modal: true, overlay: { backgroundColor: '#000', opacity: 0.05 }, dialogClass: "enjoosite_dialog", title: title, height: 125, resizable: false }
        jQuery.extend(settings, options);
        $("#enjooSite_PopupWindow").dialog(settings).show();
        $("#enjooSite_PopupWindow .enjoosite_dialog_closebar a").click(function(e) { $("#enjooSite_PopupWindow").hide(); return false; });
        $("div.enjoosite_dialog,#enjooSite_PopupWindow").css({ height: "auto" });
        if (typeof ($("#enjooSite_PopupWindow").data("activeContentId")) != "undefined") {
            if ($("#enjooSite_PopupWindow").data("activeContentId") != contentId) {
                $(String.format("#{0}", $("#enjooSite_PopupWindow").data("activeContentId"))).hide().appendTo($("body"));
            }
        }
        $("#enjooSite_PopupWindow").data("activeContentId", contentId);
        $(String.format("#{0}", contentId)).show().appendTo($("#enjooSite_PopupWindow>.enjoosite_dialog_content").empty());
        var popupWin = $("#enjooSite_PopupWindow").parents("div.enjoosite_dialog");
        $(popupWin).css("top", (parseInt($(popupWin).css("top")) - (parseInt($("#enjooSite_PopupWindow>.enjoosite_dialog_content").height())) / 2));
    }
    this["close"] = function(e) {
        $("#enjooSite_PopupWindow").dialog("close");
    }
}

//  URL地址验证
function isURL(str_url) {
    var strRegex = "^((https|http|ftp|rtsp|mms)://)"
    + "(([0-9a-z_!~*’().&=+$%-]+: )?[0-9a-z_!~*’().&=+$%-]+@)?" //ftp的user@
    + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
    + "|" // 允许IP和DOMAIN（域名）
    + "([0-9a-z_!~*’()-]+\.)*" // 域名- www.
    + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
    + "[a-z]{2,6})" // first level domain- .com or .museum
    + "(:[0-9]{1,4})?" // 端口- :80

    var re = new RegExp(strRegex);

    if (re.test(str_url)) {
        return (true);
    } else {
        return (false);
    }
};

function numberTextBox(element) {
    var reg = /^[1-9]d*|0$/;
    if (!reg.test($(element).val())) {
        $(element).val($(element).attr("oldListCount"));
    }
}
