﻿var Util = new Object();
Util.getUserAgent = navigator.userAgent;
Util.isGecko = Util.getUserAgent.indexOf("Gecko") != -1;
Util.getOffset = function(el, isLeft) {
	var retValue = 0;
	while (el != null) {
		retValue += el["offset" + (isLeft ? "Left" : "Top")];
		el = el.offsetParent;
	}
	return retValue;
};
Util.bindFunction = function(el, fucName) {
	return function () {
		return el[fucName].apply(el, arguments);
	};
};
Util.re_calcOff = function(el) {
	for (var i = 0; i < Util.dragArray.length; i++) {
		var ele = Util.dragArray[i];
		ele.elm.pagePosLeft = Util.getOffset(ele.elm, true);
		ele.elm.pagePosTop = Util.getOffset(ele.elm, false);
	}
	var nextSib = el.elm.nextSibling;
	while (nextSib) {
		nextSib.pagePosTop -= el.elm.offsetHeight;
		nextSib = nextSib.nextSibling;
	}
};
Util.hide = function() {
	Util.rootElement.style.display = "none";
};
Util.show = function() {
	Util.rootElement.style.display = "";
};
ghostElement = null;
getGhostElement = function() {
	if (!ghostElement) {
		ghostElement = document.createElement("div");
		ghostElement.style.border = "2px dashed #aaa";
		ghostElement.innerHTML = "&nbsp;";
	}
	return ghostElement;
};
function draggable(el) {
	this._dragStart = start_Drag;
	this._drag = when_Drag;
	this._dragEnd = end_Drag;
	this._afterDrag = after_Drag;
	this._close = remove;
	this._minimize = minimize;
	this._setting = setting;
	this._confirmSetting = confirmSetting;
	this._inputFilter = inputFilter;
	this.elm = el;
	this.header = document.getElementById(el.id + "_h");
	this.closeButton = document.getElementById(el.id + "_c");
	this.minimizeButton = document.getElementById(el.id + "_m");
	this.settingButton = document.getElementById(el.id + "_s");
	this.content = document.getElementById(el.id + "_content");
	this.setting = document.getElementById(el.id + "_setting");
	var titleLink = this.elm.getElementsByTagName("a")[0];
	Util.iframeArray[el.id] = this.elm.getElementsByTagName("iframe")[0];
	if (this.header) {
		this.header.style.cursor = "move";
        Drag.init(this.header, this.elm);
		this.elm.onDragStart = Util.bindFunction(this, "_dragStart");
		this.elm.onDrag = Util.bindFunction(this, "_drag");
		this.elm.onDragEnd = Util.bindFunction(this, "_dragEnd");
	}
	if (this.closeButton) {
		this.closeButton.style.cursor = "pointer";
		addButton(this.closeButton, this.header);
		this.closeButton.onclick = Util.bindFunction(this, "_close");
	}
	if (this.minimizeButton) {
		this.minimizeButton.style.cursor = "pointer";
		addButton(this.minimizeButton, this.header);
		this.minimizeButton.onclick = Util.bindFunction(this, "_minimize");
	}
	if (this.setting) {
		for (var i=0; i<this.setting.length; i++)
			if (this.setting[i].getAttribute('Filter'))
				this.setting[i].onkeydown = Util.bindFunction(this, "_inputFilter");
		var confirmButton = document.getElementById(el.id + "_confirm");
		confirmButton.style.cursor = "pointer";
		confirmButton.onclick = Util.bindFunction(this, "_confirmSetting");
		var cancelButton = document.getElementById(el.id + "_cancel");
		cancelButton.style.cursor = "pointer";
		cancelButton.onclick = Util.bindFunction(this, "_setting");
		this.settingButton.style.cursor = "pointer";
		addButton(this.settingButton, this.header);
		this.settingButton.onclick = Util.bindFunction(this, "_setting");
	}
	if (titleLink) {
		addButton(titleLink, this.header);
	}
};
function start_Drag() {
	Util.re_calcOff(this);
	this.origNextSibling = this.elm.nextSibling;
	var _ghostElement = getGhostElement();
	var offH = this.elm.offsetHeight;
	if (Util.isGecko) 
		offH -= parseInt(_ghostElement.style.borderTopWidth) * 2;
	var offW = this.elm.offsetWidth;
	var offLeft = Util.getOffset(this.elm, true);
	var offTop = Util.getOffset(this.elm, false);
	Util.hide();
	this.elm.style.width = offW + "px";
	_ghostElement.style.height = offH + "px";
	_ghostElement.style.marginBottom = this.elm.style.marginBottom;
	this.elm.parentNode.insertBefore(_ghostElement, this.elm.nextSibling);
	this.elm.style.position = "absolute";
	this.elm.style.zIndex = 100;
	this.elm.style.left = offLeft + "px";
	this.elm.style.top = offTop + "px";
	Util.rootElement.className = "highlight";
	Util.show();
	this.elm.style.filter = "alpha(opacity=70)";
	this.elm.style.opacity = 0.7;
	return false;
};
function when_Drag(clientX, clientY, MouseX) {
	var found = null;
	var max_distance = 100000000;
	for (var i = 0; i < Util.dragArray.length; i++) {
		var ele = Util.dragArray[i];
		if (ele == this) continue;
		if (this.elm.offsetWidth != ele.elm.offsetWidth)
			var distance = Math.min(Math.pow(clientX + MouseX - MouseX * ele.elm.offsetWidth / this.elm.offsetWidth - ele.elm.pagePosLeft, 2), Math.pow(clientX - ele.elm.pagePosLeft, 2)) + Math.pow(clientY - ele.elm.pagePosTop, 2);
		else
			var distance = Math.pow(clientX - ele.elm.pagePosLeft, 2) + Math.pow(clientY - ele.elm.pagePosTop, 2);
		if (isNaN(distance)) continue;
		if (distance < max_distance) {
			max_distance = distance;
			found = ele;
		}
	}
	var _ghostElement = getGhostElement();
	if (found != null && _ghostElement.nextSibling != found.elm) {
		if (/^(Column)[0-9]+$/.test(_ghostElement.nextSibling.id)) 
			if (_ghostElement.previousSibling == this.elm) {
				if (this.elm.previousSibling != null) 
					this.elm.previousSibling.style.marginBottom = "";
			} else if (_ghostElement.previousSibling != null) 
				_ghostElement.previousSibling.style.marginBottom = "";
		if (/^(Column)[0-9]+$/.test(found.elm.id)) 
			if (found.elm.previousSibling == this.elm) {
				if (this.elm.previousSibling != null)
					this.elm.previousSibling.style.marginBottom = "10px";
			} else if (found.elm.previousSibling != null) {
				found.elm.previousSibling.style.marginBottom = "10px";
			}
		found.elm.parentNode.insertBefore(_ghostElement, found.elm);
		if (/^(Gadget)[0-9]+$/.test(found.elm.id)) 
			_ghostElement.style.marginBottom = "10px";
		else
			_ghostElement.style.marginBottom = "";
	}
};
function end_Drag() {
	if (this._afterDrag()) {
		var URL = 'move.php?id=' + this.elm.id.replace('Gadget', 'G');
		if (/Column[0-9]+/i.test(this.elm.nextSibling.id)) {
			if (this.elm.previousSibling == null)
				URL += '&previousSibling=' + this.elm.nextSibling.id.replace('Column', 'C');
			else
				URL += '&previousSibling=' + this.elm.previousSibling.id.replace('Gadget', 'G');
		} else
			URL += '&nextSibling=' + this.elm.nextSibling.id.replace('Gadget', 'G');
		AJAX(Ready, URL + '&pid=' + pid + '&tid=' + tid);
	}
	return true;
};
function after_Drag() {
	var returnValue = false;
	Util.hide();
	this.elm.style.position = "";
	this.elm.style.width = "";
	this.elm.style.zIndex = "";
	this.elm.style.filter = "";
	this.elm.style.opacity = "";
	var ele = getGhostElement();
	this.elm.style.marginBottom = ele.style.marginBottom;
	if (ele.nextSibling != this.origNextSibling) {
		ele.parentNode.insertBefore(this.elm, ele.nextSibling);
		returnValue = true;
	}
	Util.rootElement.className = "";
	ele.parentNode.removeChild(ele);
	Util.show();
	return returnValue;
};
var Drag = {
	obj:null, 
	init:function(elementHeader, element) {
		elementHeader.onmousedown = Drag.start;
		elementHeader.obj = element;
		if (isNaN(parseInt(element.style.left))) 
			element.style.left = "0px";
		if (isNaN(parseInt(element.style.top))) 
			element.style.top = "0px";
		element.onDragStart = new Function();
		element.onDragEnd = new Function();
		element.onDrag = new Function();
	},
	start:function(event) {
		var element = Drag.obj = this.obj;
		event = Drag.fixE(event);
		if (event.which != 1) {
			return true;
		}
		element.onDragStart();
		element.MouseX = event.clientX - parseInt(element.style.left);
		element.MouseY = event.clientY - parseInt(element.style.top);
		document.onmouseup = Drag.end;
		document.onmousemove = Drag.drag;
		return false;
	}, 
	drag:function(event) {
		event = Drag.fixE(event);
		if (event.which == 0) 
			return Drag.end();
		var element = Drag.obj;
		var newX = event.clientX - element.MouseX;
		var newY = event.clientY - element.MouseY;
		element.style.left = newX + "px";
		element.style.top = newY + "px";
		element.onDrag(newX, newY, element.MouseX);
		return false;
	},
	end:function(event) {
		document.onmousemove = null;
		document.onmouseup = null;
		var _onDragEndFuc = Drag.obj.onDragEnd();
		Drag.obj = null;
		window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
		return _onDragEndFuc;
	}, 
	fixE:function(ig_) {
		if (typeof(ig_)== "undefined") 
			ig_ = window.event;
		if (typeof(ig_.layerX) == "undefined") 
			ig_.layerX = ig_.offsetX;
		if (typeof(ig_.layerY) == "undefined") 
			ig_.layerY = ig_.offsetY;
		if (typeof(ig_.which) == "undefined") 
			ig_.which = ig_.button;
		return ig_;
	}
};
function addButton(Button, elementHeader) {
	Button.onmouseover = function() {
		elementHeader.onmousedown = null;
	}
	Button.onmouseout = function() {
		elementHeader.onmousedown = Drag.start;
	}
};
function remove() {
	if (confirm('是否確定刪除這個工具?')) 
		for (var i = 0; i < Util.dragArray.length; i++)
			if (Util.dragArray[i] == this) {
				this.elm.parentNode.removeChild(this.elm);
				AJAX(Ready, 'del.php?id=' + this.elm.id.replace('Gadget', 'G') + '&pid=' + pid);
				if (Util.rootColumn > i) Util.rootColumn--;
				Util.dragArray.splice(i, 1);
			}
};
function minimize() {
	if (this.content.style.display == 'none') 
		this.content.style.display = '';
	else {
		if (this.setting) this.setting.style.display = 'none';
		this.content.style.display = 'none';
	}
};
function inputFilter(Event) {
	if (window.event) {
		var Key = event.keyCode;
		var ele = event.srcElement;
	} else {
		var Key = Event.which;
		var ele = Event.target;
	}
	if (event.ctrlKey && (Key == 86 || Key == 67)) return true;
	var Filter = ele.getAttribute('Filter').replace(/\[Chi\]/i, '\u00E5\u4E00-\u9FA5').replace(/\[Eng\]/i, 'a-zA-Z').replace(/\[Num\]/i, '0-9\u0060-\u0069');
	Filter = new RegExp('[\u0008\u0009\u0010\u0011\u0014\u001B\u0023-\u0028\u002E' + Filter + ']');
	return Filter.test(String.fromCharCode(Key));
}
function setting() {
	if (this.setting.style.display == 'none') {
		this.content.style.display = '';
		this.setting.style.display = '';
		var valueName;
		var temp;
		var src = Util.iframeArray[this.elm.id].src;
		for (var i=0; i<this.setting.length; i++) {
			valueName = this.setting[i].id.match(/[^_]+$/);
			if (this.setting[i].tagName.toLowerCase() == 'input' && this.setting[i].getAttribute('type').toLowerCase() == 'checkbox') {
				if (parseInt(src.match(RegExp('[?&]' + valueName[0] + '=([^&]*)', 'i'))[1]) > 0) this.setting[i].checked = true;
				else this.setting[i].checked = false;
			} else {
				switch (valueName[0].toLowerCase()) {
					case 'zgheight':
						this.setting[i].value = this.content.offsetHeight;
						break;
					case 'zglogo':
						temp = this.header.rows[0].cells[0].innerHTML.match(/background="?([^"^>]+)"?/i);
						if (temp) this.setting[i].value = temp[1];
						break;
					case 'zgtitle':
						temp = this.header.rows[0].cells[1].innerHTML.match(/>([^<]+)</i);
						if (temp) this.setting[i].value = temp[1];
						else this.setting[i].value = this.header.rows[0].cells[1].innerHTML;
						break;
					case 'zglink':
						temp = this.header.rows[0].cells[1].innerHTML.match(/popupIframe.show\('[^']*', ?'([^']*)'/i);
						if (temp) this.setting[i].value = temp[1];
						break;
					default:
						temp = src.match(RegExp('[?&]' + valueName[0] + '=([^&]*)', 'i'));
						if (temp) this.setting[i].value = decodeURIComponent(temp[1]);
				}
			}
		}
	} else
		this.setting.style.display = 'none';
};
function confirmSetting() {
	var valueName;
	var src = Util.iframeArray[this.elm.id].src;
	var url = '';
	var temp;
	var oldValue, newValue;
	for (var i=0; i<this.setting.length; i++) {
		valueName = this.setting[i].id.match(/[^_]+$/);
		if (this.setting[i].tagName.toLowerCase() == 'input' && this.setting[i].getAttribute('type').toLowerCase() == 'checkbox') {
			oldValue = src.match(RegExp('[?&]' + valueName[0] + '=([^&]*)', 'i'));
			if (oldValue) 
				if (this.setting[i].checked) {
					if (!parseInt(oldValue[1])) {
						if (oldValue[1] == '')
							newValue = oldValue[0] + 1;
						else
							newValue = oldValue[0].replace(/[^=]+$/, 1);
						url += '&' + valueName + '=1';
						src = src.replace(oldValue[0], newValue);
					}
				} else {
					if (parseInt(oldValue[1])) {
						newValue = oldValue[0].replace(/[^=]+$/, 0);
						url += '&' + valueName + '=0';
						src = src.replace(oldValue[0], newValue);
					}
				}
			else
				if (this.setting[i].checked) {
					if (/\?/.test(src)) 
						src += '&' + valueName[0] + '=1';
					else
						src += '?' + valueName[0] + '=1';
					url += '&' + valueName + '=1';
				}
		} else {
			newValue = encodeURIComponent(this.setting[i].value.replace('<', '&lt;').replace('>', '&gt;'));
			switch (valueName[0].toLowerCase()) {
				case 'zgheight':
					if (this.setting[i].value != this.content.offsetHeight) {
						url += '&' + valueName + '=' + newValue;
						if (this.content.tagName == 'IFRAME') {
							Util.iframeArray[this.elm.id].style.height = newValue + 'px';
						} else {
							Util.iframeArray[this.elm.id].style.height = (newValue - 10) + 'px';
						}
					}
					break;
				case 'zglogo':
					temp = this.header.rows[0].cells[0].innerHTML.match(/background="?([^"^ ]+)"?/i);
					if (temp) oldValue = temp[1];
					else oldValue = '';
					if (this.setting[i].value != oldValue) {
						if (this.setting[i].value == '') 
							this.header.rows[0].cells[0].innerHTML = '<img src="image/gadgets/icon/ziondaily.gif" width="16" height="16" />';
						else
							this.header.rows[0].cells[0].innerHTML = '<table cellspacing="0" cellpadding="0"><tr><td><img src="image/space.gif" width="1" height="1" /></td><td style="background:url(' + this.setting[i].value + ') -1px 0"></td><td><img src="image/space.gif" width="1" height="1" /></td></tr><tr><td colspan="3" style="background:url(' + this.setting[i].value + ') 0 -1px"><img src="image/space.gif" width="16" height="14" /></td></tr><tr><td></td><td style="background:url(' + this.setting[i].value + ') -1px -15px"><img src="image/space.gif" width="14" height="1" /></td><td></td></tr></table>';
						url += '&' + valueName + '=' + newValue;
					}
					break;
				case 'zgtitle':
					temp = this.header.rows[0].cells[1].innerHTML.match(/>([^<]+)</i);
					if (temp) oldValue = temp[1];
					else oldValue = this.header.rows[0].cells[1].innerHTML;
					if (this.setting[i].value != oldValue) {
						if (this.setting[i].value == '')
							this.header.rows[0].cells[1].innerHTML = '&nbsp;';
						else
							this.header.rows[0].cells[1].innerHTML = this.header.rows[0].cells[1].innerHTML.replace(RegExp(oldValue.replace(/([\\\^$*+?{}.|()\[\]])/g, '\\$1'), 'g'), this.setting[i].value.replace('<', '&lt;').replace('>', '&gt;'));
						url += '&' + valueName + '=' + newValue;
					}
					break;
				case 'zglink':
					temp = this.header.rows[0].cells[1].innerHTML.match(/popupIframe.show\('[^']*', ?'([^']*)'/i);
					if (temp) oldValue = temp[1];
					else oldValue = '';
					if (this.setting[i].value != oldValue) {
						if (temp) {
							this.header.rows[0].cells[1].innerHTML = this.header.rows[0].cells[1].innerHTML.replace(oldValue, this.setting[i].value);
						} else {
							this.header.rows[0].cells[1].innerHTML = '<a href="javascript:" onclick="popupIframe.show(\'' + this.header.rows[0].cells[1].innerHTML + '\', \'' + + '\');" class="headerText">' + this.header.rows[0].cells[1].innerHTML + '</a>';
						url += '&' + valueName + '=' + newValue;
						}
					}
					break;
				default:
					oldValue = src.match(RegExp('[?&]' + valueName[0] + '=([^&]*)', 'i'));
					if (oldValue) {
						if (this.setting[i].value != oldValue[1]) {
							url += '&' + valueName + '=' + newValue;
							if (oldValue[1] == '')
								newValue = oldValue[0] + newValue;
							else
								newValue = oldValue[0].replace(/[^=]+$/, newValue);
							src = src.replace(oldValue[0], newValue);
						}
					} else {
						if (this.setting[i].value != '') {
							url += '&' + valueName + '=' + newValue;
							if (/\?/.test(src)) 
								src += '&' + valueName[0] + '=' + this.setting[i].value;
							else
								src += '?' + valueName[0] + '=' + this.setting[i].value;
						}
					}
			}
		}
	}
	if (url != '') 
		AJAX(function() {}, 'setting.php?id=' + this.elm.id.match(/[0-9]+/)[0] + url);
	if (Util.iframeArray[this.elm.id].src != src)
		Util.iframeArray[this.elm.id].src = src;
	this.setting.style.display = 'none';
};
function addStuff(id) {
	AJAX(function(html) {
		if (Ready(html)) {
			var tempElement = document.createElement('body');
			var ele = Util.dragArray[Util.rootColumn].elm;
			if (ele.previousSibling != null) 
				html = html.replace('<div id="Gadget', '<div style="margin-bottom: 10px" id="Gadget');
			document.getElementById('i1').value = html;
			tempElement.innerHTML = html;
			tempElement = tempElement.getElementsByTagName("div")[0];
			ele = ele.parentNode;
			ele.insertBefore(tempElement, ele.getElementsByTagName("div")[0]);
			initDrag(Util.rootElement);
		}
	}, 'gadget.php?id=' + id + (zpid == '_iframeProxy' ? '' : '&zpid=' + zpid) + '&pid=' + pid);
};
function initDrag(el) {
	Util.rootElement = el;
	Util.dragArray = new Array();
	Util.iframeArray = new Array();
	var ele = el.getElementsByTagName("div");
	var counter = 0;
	for (var i = 0; i < ele.length; i++)
		if (/^(Column|Gadget)[0-9]+$/.test(ele[i].id)) {
			Util.dragArray[counter] = new draggable(ele[i]);
			if (ele[i].id == "Column1") 
				Util.rootColumn = counter;
			counter++;
		}
};