var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;

//variable to store location of each widget
var position = new Array();
var memberId = '';

DDWidget = function(id, sGroup, config) {
	DDWidget.superclass.constructor.call(this, id, sGroup, config);
	var el = this.getDragEl();
	
	Dom.setStyle(el, "opacity", 0.5); // The proxy is slightly transparent
	this.goingUp = false;
	this.lastY = 0;
};
YAHOO.extend(DDWidget, YAHOO.util.DDProxy, {

	startDrag: function(x, y){

		// make the proxy look like the source element
		var dragEl = this.getDragEl();
		var clickEl = this.getEl();
		Dom.setStyle(clickEl, "opacity", 0.2);
		dragEl.innerHTML = clickEl.innerHTML;
		
		Dom.setStyle(dragEl, "border", "0");
		Dom.setStyle(dragEl, "textAlign", "left");
	},

	endDrag: function(e){

		var srcEl = this.getEl();
		var proxy = this.getDragEl();

		// Show the proxy element and animate it to the src element's location
		Dom.setStyle(proxy, "visibility", "");
		var a = new YAHOO.util.Motion( 
			proxy, { 
				points: { 
					to: Dom.getXY(srcEl)
				}
			}, 
			0.5, 
			YAHOO.util.Easing.easeOut 
		)
		var thisid = this.id;

		// destroy the proxy and show the source element when finished with the animation
		a.onComplete.subscribe(function() {
				proxy.innerHTML = '';
				Dom.setStyle(proxy.id, "visibility", "hidden");
				Dom.setStyle(thisid, "visibility", "");
				Dom.setStyle(thisid, "opacity", 1);
				Dom.get(thisid).style.removeAttribute('filter'); //to restore ie7 clearType
				Dom.setStyle(thisid, "font-size", "18px");
			});
		a.animate();
		
		//make a call to db
		updateDBRank();
	},

	onDragDrop: function(e, id) {
		
	},
	onDrag: function(e) {

		// Keep track of the direction of the drag for use during onDragOver
		var y = Event.getPageY(e);

		if (y < this.lastY) {
			this.goingUp = true;
		} else if (y > this.lastY) {
			this.goingUp = false;
		}

		this.lastY = y;
	},
	
	onDragOver: function(e, id) {
	
		var srcEl = this.getEl();
		var destEl = Dom.get(id);
		var srcParent = srcEl.parentNode;
		var oldNextSibling = srcEl.nextSibling;
		
		// The position of the cursor at the time of the drop (YAHOO.util.Point)
		var pt = DDM.interactionInfo.point;
		// The region occupied by the source element at the time of the drop
		var region = DDM.interactionInfo.sourceRegion;

		// When the DD is over a draggable object, we do an insert above or below
		if (!region.intersect(pt) && destEl.id.substr(0,4) == "widg") {
			var p = destEl.parentNode;
			
			if (this.goingUp) {
				p.insertBefore(srcEl, destEl); // insert above	
				//update the position table
			} else {
				p.insertBefore(srcEl, destEl.nextSibling); // insert below
			}
			DDM.refreshCache();
			//update the position table
			updatePosition(srcEl, oldNextSibling);
		}
		
		else if (id != srcParent.id && id.substr(0,3) == "col"){
			destEl.appendChild(srcEl);
			DDM.refreshCache();
			updatePosition(srcEl, oldNextSibling);
		}

		//to extend the left column if there's no elements in it. For IE6.
		if (srcParent.id == "col_1"){
			var regionleft = Dom.getRegion(Dom.get("col_1"));
			if (regionleft.bottom - regionleft.top <= 250) Dom.setStyle(Dom.get("col_1"), "height", "250px");
		}
	}
});

function updatePosition(src, oldSibling){ //direction moved up = 1; down = 0.
	var srcId = src.id.split("_")[1];
	var widgId;
	
	//update src widget's old col ranking. Move those below it one rank up
	while (oldSibling){
		if (oldSibling.id){
			widgId = oldSibling.id.split("_")[1];
			position[widgId].rank--;
			position[widgId].changed = 1;
		}
		oldSibling = oldSibling.nextSibling;
	}
	
	//Update src widget's position details
	var previousNode = src.previousSibling;
	while (previousNode){
		if (previousNode.id){
			widgId = previousNode.id.split("_")[1];
			position[srcId].rank = position[widgId].rank + 1;
			position[srcId].col = position[widgId].col;
			break;
		}
		else{
			position[srcId].rank = 1;
		}
		previousNode = previousNode.previousSibling;
	}
	
	//column
	var col = src.parentNode.id.split("_")[1];
	position[srcId].col = col;
	position[srcId].changed = 1;
	
	//update src widget's new col ranking. Move those below it one rank down
	var affectedNode = src.nextSibling;
	while (affectedNode){
		if (affectedNode.id){
			widgId = affectedNode.id.split("_")[1];
			position[widgId].rank++;
			position[widgId].changed = 1;
		}
		affectedNode = affectedNode.nextSibling;
	}
}

//update the db with the latest rank
function updateDBRank(){
	//do a ajax call to the db to save the settings if there is a member ID
	if (memberId != ''){

		var callback = 
		{ 
			success: function(o) {
						//alert(o.responseText)
					}, 
			failure: function(o){
						alert("The page is unable to save the widgets layout. Please try again. Error:" + o.statusText)
					}, 
			argument: [''] 
		} 
		
		//arrange the position data
		var data = "data=";
		for (i in position){
			if (position[i].changed == 1){
				data += i + "," + position[i].col + "," + position[i].rank + ";";
			}
		}
		data = data.substring(0,data.length-1);
		YAHOO.util.Connect.asyncRequest('POST', '/save_widget.php', callback, data); 
	}
	
}
function closeWidget(e){
	if (confirm("Close this widget?")){
		var wid = this.id.split("_")[1];
				
		//update the rank of those below it.
		var oldSibling = Dom.get("widg_" + wid).nextSibling;
		while (oldSibling){
			if (oldSibling.id){
				widgId = oldSibling.id.split("_")[1];
				position[widgId].rank--;
				position[widgId].changed = 1;
			}
			oldSibling = oldSibling.nextSibling;
		}
		updateDBRank();
		
		//remove the widget from db
		var callback = 
			{ 
				success: function(o) {
					var anim = new YAHOO.util.Anim('widg_'+wid, { 
						opacity: { to: 0 }  
					}, 0.5, YAHOO.util.Easing.easeOut); 
					anim.onComplete.subscribe(function() {
						Dom.setStyle("widg_"+wid, "display", "none");
					});
					anim.animate();
				}, 
				failure: function(o){
							alert("Unable to remove widget. Please try again. Error:" + o.statusText)
						}
			}
		var data = "close=1&wid=" + wid;
		YAHOO.util.Connect.asyncRequest('POST', '/save_widget.php', callback, data);
	}
}
function expandOption(e){	
	var wid = this.id.split("_")[1];
	var optionbody = Dom.get("woptionb_" + wid);

	if (Dom.getStyle(optionbody,'display') == "none")
		Dom.setStyle(optionbody, "display", "block");
	else
		Dom.setStyle(optionbody, "display", "none");
}
function saveSettings(wid, url){ //save the settings for widget options
	var filter1string = '', filter1url = '';
	var filter2string = '';
	var filter3string = '', filter3url = '';
	var itemstring = '';
	var title = '';
	for (var i=0; i<document.forms.length; i++){
		if (document.forms[i].name == "optionform1_" + wid){ //for filter1
			var optionform = document.forms[i];
			for(var j=0;j< optionform.length;j++){
				if (optionform[j].checked){
					filter1string += optionform[j].value + ",";
					switch (optionform[j].value){
						case '1':
							filter1url +="&channels=1";
							break;
						case '2':
							filter1url +="&enterprisenetworking=1";
							break;
						case '3':
							filter1url +="&enterprisesecurity=1";
							break;
						case '4':
							filter1url +="&mobilenavigation=1";
							break;
						case '5':
							filter1url +="&mobility=1";
							break;
						case '6':
							filter1url +="&netbook=1";
							break;
						case '7':
							filter1url +="&pc=1";
							break;
						case '8':
							filter1url +="&smartphone=1";
							break;
						case '9':
							filter1url +="&unifiedcommunications=1";
							break;
					}
				}
			}
		}
		else if (document.forms[i].name == "optionform2_" + wid){ //for filter2, a select element
			var selectMenu = document.forms[i].filter2;
			filter2string = selectMenu.options[selectMenu.selectedIndex].value;
		}
		else if (document.forms[i].name == "optionform3_" + wid){ //for filter3
			var optionform = document.forms[i];
			for(var j=0;j< optionform.length;j++){
				if (optionform[j].checked){
					filter3string += optionform[j].value + ",";
					switch (optionform[j].value){
						case '1':
							filter3url += "&data=1";
							break;
						case '2':
							filter3url += "&marketoverview=1";
							break;
						case '3':
							filter3url += "&misc=1";
							break;
						case '4':
							filter3url += "&pulse=1";
							break;
						case '5':
							filter3url += "&report=1";
							break;
						case '6':
							filter3url += "&surveyresult=1";
							break;
						case '7':
							filter3url += "&pollresult=1";
							break;
						case '8':
							filter3url += "&video=1";
							break;
					}
				}
			}
		}
		else if (document.forms[i].name == "itemform_" + wid){ //for items
			var optionform = document.forms[i];
			itemstring = optionform.items.value;
		}
		else if (document.forms[i].name == "titleform_" + wid){ //for custom titles
			var optionform = document.forms[i];
			title = optionform.title.value;
			if (title.length >45 || title == ''){
				alert("Please enter a title not longer than 45 characters");
				return false;
			}
			
		}
	}
	filter1string = filter1string.substr(0, filter1string.length-1);
	filter3string = filter3string.substr(0, filter3string.length-1);

	//send the filterstring to db and get the filtered list back
	var paragraph = Dom.get("paragraph_" + wid);
	paragraph.innerHTML = "<div style='text-align:center'><img src='/images/loading.gif'</div>";
	
	var callback = 
		{ 
			success: function(o) {
				//close the option menu
				Dom.setStyle("woptionb_" + wid, "display", "none");
				
				//change the title if needed
				var titleE = Dom.get("title_" + wid);
				if (title != '') titleE.innerHTML = title;
				if ((filter1url != '' || filter3url != '') && titleE.href != ''){
					titleE.href += filter1url + filter3url;
				}
				if (o.responseText== 'Reloading page') window.location.href="/";
				else paragraph.innerHTML = o.responseText;
			}, 
			failure: function(o){
				alert("Unable to update widget. Please try again. Error:" + o.statusText)
			}
		}
	var data = "save=1&filter1=" +filter1string + "&filter2=" +filter2string + "&filter3=" +filter3string +"&items="+itemstring +"&title="+title +"&wid=" + wid;
	YAHOO.util.Connect.asyncRequest('POST', "/widgets/" + url, callback, data);
}

function setDD(id,col,rank){
	dd = new DDWidget("widg_" + id);
	dd.setHandleElId("whead_" + id);
	Event.addListener("wclose_" + id, "click", closeWidget); 
	Event.addListener("woption_" + id, "click", expandOption); 
	
	//store the position of the widget
	position[id] = new Object;
	position[id].changed = 0;
	position[id].col = col;
	position[id].rank = rank;
}

function changeTab(node){
	var clickedtab = node.id;
	if (clickedtab == activetab) return; //do nothing
	
	Dom.removeClass(Dom.get(activetab), "selected");
	activetab = clickedtab;
	Dom.addClass(node, "selected");
	
	var tabarea = Dom.get("tabarea");
	tabarea.innerHTML = Dom.get(clickedtab + "_content").innerHTML;
}

YAHOO.util.Event.onDOMReady(function() {
	//set up the drag and drop elements
	new YAHOO.util.DDTarget("col_1"); 
	new YAHOO.util.DDTarget("col_2");
	new YAHOO.util.DDTarget("col_3");
});