// Web App Path
var APP_PATH = "/DesktopModules/Cool_News";

//Load the Yahoo UI library - Used for AJAX POST request, Animating open/close of document item
document.write("<script type='text/javascript' src='"+APP_PATH+"/js/yahoo-min.js'></script>");
document.write("<script type='text/javascript' src='"+APP_PATH+"/js/connection-min.js'></script>");
document.write("<script type='text/javascript' src='"+APP_PATH+"/js/dom-min.js'></script>");
document.write("<script type='text/javascript' src='"+APP_PATH+"/js/event-min.js'></script>");
document.write("<script type='text/javascript' src='"+APP_PATH+"/js/animation-min.js'></script>");

// URL to retrieve document items via POST
var DOCUMENT_ITEM_VIEW_URL = APP_PATH+"/NewsViewItem.aspx";
var DOCUMENT_ITEM_EDIT_URL = APP_PATH+"/NewsEdit.aspx";

// Used to keep track of timer values and mouse coordinates to scroll the window
var slowCheck, fastCheck;
var mouse = {x:0, y:0};

// The currently active item that is being downloaded
var ActiveObj = {mID:0, iID:0, tvgObj: null, reqCon: null};

// Misc
var ANIMATE_TOGGLE = true;
var IsSortDragging = false;

// Highlight the attached file region when mouse is over
function HI(type, obj)
{
	if (obj)
	{
		if (type)
			obj.style.backgroundColor="#fffce2";
		else
			obj.style.backgroundColor="";
	}
}

// Connect to the attached file given the link.  A new window is opened
function AF(val)
{
	if (!IsSortDragging && val)
	{
		var openWin = window.open(val);
		
		// See if the window opened ok (not popup blocked).  If didnt then just redirect page
		if (!CheckOpenWindow(openWin))
			location.href = val;	
	}	
	
	IsSortDragging = false;
	document.onselectstart = null;
}

// The edit link is clicked.  Jump to the Edit Page for the item
function ED(tID, mID, iID)
{
	location.href = DOCUMENT_ITEM_EDIT_URL + "?tabID="+tID+"&ItemID="+iID+"&mid="+mID;
}

// Toggle View between short/long display when user clicks the +/- graphic or type >= 1 (1=more clicked, 2=download complete)
function TV(tvgObj, mID, iID, type, sortMove)
{
	// Abort any currently active download.  This helps in cae user clicks another +/- or when download is complete to hide the progress
	AbortCurrentDownload(mID, iID);

	// Get the long and short text objects for this caller, if any
	var docTextShort = document.getElementById("DocTextShort_"+mID+","+iID);
	var docTextLong  = document.getElementById("DocTextLong_"+mID+","+iID);
	
	// Get the toggle view graphic object if not already provided (ie. More link clicked)
	if (tvgObj == null || tvgObj.id != "tvg_"+mID+","+iID)
		tvgObj = document.getElementById("tvg_"+mID+","+iID);

	// Determine the current view for this requesting object -- is it currently collapsed or expanded or was type set
	// Type is used by the (More) link [1] and StartDownload completed successfully [2]. It is used to adjust the behavior of 
	// this function and AbortCurrentDownload = to ignore resetting the Collapse/Expand graphic and/or reveal the long description.
	if (!sortMove && (tvgObj.className == "Collapse" || type))
	{
		// Change the toggle view graphic
		tvgObj.className = "Expand";

		// Does a long text description not exist?  If so retrieve it
		if (!docTextLong)
			StartDownload(tvgObj, mID, iID)	
		else
		{
			if (ANIMATE_TOGGLE)
				AnimateDocContents(1, docTextShort, docTextLong);
			else
			{	
				docTextShort.style.display = "none";
				docTextLong.style.display  = "block";
			}	
		}
	}
	else if (tvgObj.className == "Expand")
	{
		// If this is not a sort move then can perform Animation if necessary
		if (!sortMove && ANIMATE_TOGGLE)
			AnimateDocContents(0, docTextLong, docTextShort);
		else
		{
			if (docTextLong)
				docTextLong.style.display = "none";	
			docTextShort.style.display = "block";		
		}	

		// Change the toggle view icon to collapsed
		tvgObj.className = "Collapse";
	}
}

// Animate open/close the DocTextLong area once the data is retrieved
function AnimateDocContents(type, HideThisObj, ShowThisObj)
{
	var objHeight = GetObjHeight(ShowThisObj);
	var myAnim;

	// Animate on
	if (type == 1)
	{
		// Hide HideThisObj and reveal ShowThisObj but sized to HideThisObj
		with (ShowThisObj.style)
		{
			height  = HideThisObj.offsetHeight;
			HideThisObj.style.display = "none";
			display = "block";
		}

		myAnim = new YAHOO.util.Anim(ShowThisObj, {height: { to: objHeight }},.4, YAHOO.util.Easing.easeOut);		
	}
	else // Collapse it
	{
		myAnim = new YAHOO.util.Anim(HideThisObj, {height: { to: objHeight }},.3, YAHOO.util.Easing.easeOut);			

		// On anim complete hide HideThisObj and reveal ShowThisObj
		myAnim.onComplete.subscribe(function()
		{
			if (HideThisObj)
				HideThisObj.style.display = "none";
			ShowThisObj.style.display = "block";
		});
	}

	// Do the animation	
    myAnim.animate();
}

// Get the objects height by quickly showing it and rehiding it.  Seems odd but it works.  I dont see any flashing on screen.
// Shoving it off screen via position absolute temporarily doesnt seem to help.
function GetObjHeight(obj)
{
	var info = {pos: obj.style.position, left: obj.style.left, height: obj.style.height, display: obj.style.display};
	var objHeight;
	with(obj.style)
	{
		height   = "auto";
		display = "block";
		objHeight = obj.offsetHeight;		
		height  = info.height;
		display = info.display;
	}	
	return objHeight;
}

// Cancel the download process
function AbortCurrentDownload(cmID, ciID)
{
	if (ActiveObj.mID !=0 || ActiveObj.iID !=0)
	{	
		// Hide the progress bar
		DisplayProgressBar(0, null);

		// Reset the active object, and redisplay the collapse image if allowed
		with (ActiveObj)
		{
			// If the active item isnt the current item to deal with then reset the old item's collapse display
			if (cmID != mID && ciID != iID)
				tvgObj.className = "Collapse";
		
			mID = 0; 
			iID = 0; 		
			tvgObj = null;
		}	
		
		// Abort the download sequence, if any
		if (ActiveObj.reqCon)
		{
			YAHOO.util.Connect.abort(ActiveObj.reqCon, null, true);
			ActiveObj.reqCon = null;
		}	
	}	
}

// Do the AJAX download for the DocTextLong
function StartDownload(tvgObj, mID, iID)
{
	// Show the progress bar
	DisplayProgressBar(1, tvgObj);

	// Set the current active object
	ActiveObj.mID = mID; ActiveObj.iID = iID; ActiveObj.tvgObj = tvgObj;
	
	// Do Download for the module/item
	var HandleSuccessDload = function(o)
	{ 
		if(o.responseText !== undefined)
		{ 
			var mID = o.argument.mID, iID = o.argument.iID;

			// Build the new DocTextLong object and insert the response
			var parDoc = document.getElementById("DocTextShort_"+mID+","+iID).parentNode;

			var docTextLong = document.createElement("div");
			docTextLong.id = "DocTextLong_"+mID+","+iID;
			docTextLong.setAttribute("style","display:none");
			docTextLong.className = "DocTextLong";
			docTextLong.innerHTML = o.responseText.replace('div class="Attachments"', 'div class="Attachments" id="Attachments_'+mID+','+iID+'"');

			parDoc.appendChild(docTextLong);
			
			if (YAHOO.util.Dom.hasClass(document.getElementById("di_"+iID),"Admin") && document.getElementById('Attachments_'+mID+','+iID) != null)
				Sortable.create('Attachments_'+mID+','+iID,{tag:'div',overlap:'horizontal', onUpdate:SortUpdateAttachment, only:'AttachmentFile',constraint:false}, true);			

			// Call toggle view to show it on screen
			TV(ActiveObj.tvgObj, mID, iID, 1)
		} 
		else
			AbortCurrentDownload();
	} 
	
	var HandleFailDload = function(o)
	{
		AbortCurrentDownload();
	}

	var callback = 
	{ 
		success:HandleSuccessDload, 
		failure: HandleFailDload, 
		argument: {mID:mID, iID:iID}, 
		timeout: 120000
	};

	var PostData = "type=viewitem";	
	ActiveObj.reqCon = YAHOO.util.Connect.asyncRequest('POST', DOCUMENT_ITEM_VIEW_URL + "?tabID=0&ItemID=" + iID + "&mid=" + mID+ "&wversion=Staging", callback, PostData); 
}

// Show the progress bar
function DisplayProgressBar(type, tvgObj)
{
	var progAnim = document.getElementById("ProgressAnim");
	
	if (type == 1)
	{
		var progLoc = FindElementPos(tvgObj);

//		progAnim.style.top  = progLoc.top + 2;
//		progAnim.style.left = progLoc.left + 235;;
//
//		progAnim.style.display="block";
	}
	else
		progAnim.style.display="none";
}

// Get the objects x/y position
function FindElementPos(iobj)
{
	obj = iobj;

	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;

	obj = iobj;
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return {left:curleft, top:curtop};
}

// A document item has been reshuffled, so we need to AJAX post to update the dbase
function SortUpdate(obj)
{
	var HandleSuccessDload = function(o)
	{ 
		if(o.responseText !== undefined)
		{} 
	} 
	
	var HandleFailDload = function(o)
	{}

	var callback = 
	{ 
		success:HandleSuccessDload, 
		failure: HandleFailDload, 
		argument: null, 
		timeout: 120000
	};

	// Get the document items within the container
	var docItems = obj.childNodes;
	var postData = "";	

	for (var i=0; i < docItems.length; i++)
	{
		var obj2 = docItems[i];
		
		if (obj2.nodeName == "DIV" && obj.id)
		{
			var tmpID = obj2.id.match(/_(\d+)$/);
		
			if (tmpID.length > 1)
			{	
				if (postData != "") postData += "&";
				postData += "i=" + tmpID[1];
			}	
		}	
	}
	
	if (postData)
		ActiveObj.reqCon = YAHOO.util.Connect.asyncRequest('POST', DOCUMENT_ITEM_EDIT_URL + "?sort=true&tabID=" + obj.getAttribute("TabID") + "&mid=" + obj.getAttribute("ModuleID"), callback, postData); 
}

function SortUpdateAttachment(obj)
{
	var HandleSuccessDload = function(o)
	{ 
		if(o.responseText !== undefined)
		{} 
	} 
	
	// When click drag an attachment it will click the item when done.  need to cancel this
	IsAttachmentSortUpdate = true;
	
	var HandleFailDload = function(o)
	{}

	var callback = 
	{ 
		success:HandleSuccessDload, 
		failure: HandleFailDload, 
		argument: null, 
		timeout: 120000
	};

	var postData = [];
	
	// Gather all the item new sort order
	if (obj.childNodes.length > 0)
	{
		var YUD = YAHOO.util.Dom; 
		
		for (var i = 0, cnt = obj.childNodes.length; i < cnt; i++)
		{
			if (YUD.hasClass(obj.childNodes[i], "AttachmentFile"))
				postData.push(obj.childNodes[i].id.split("_")[1]);
		}
	}
	
	if (postData.length > 0)
	{
		var tempID = obj.id.match(/_(\d+),(\d+)/);
		var mID = tempID[1], iID = tempID[2];
		var tabID = 0;
		
		while (obj && !obj.getAttribute("tabid"))
			obj = obj.parentNode;
		if (obj.getAttribute("tabid"))		
			tabid = obj.getAttribute("tabid");
			
		ActiveObj.reqCon = YAHOO.util.Connect.asyncRequest('POST', DOCUMENT_ITEM_EDIT_URL + "?sort2=true&tabID=" + tabid + "&mid=" + mID + "&itemID="+iID, callback, "i="+postData.join(",")); 
	}	
}

// Document item is just about to be visually reshuffled.  Collapse the item and set up the window scrolling timers
function SortDragStart(obj)
{
	IsSortDragging = true;
	
	document.onselectstart = function() {return false;} // ie
	//document.onmousedown = function() {return false;} // mozilla	
	
	if (obj.id && obj.className != "AttachmentFile")
	{
		// Get the module ID and ItemID for this item and call TV to make sure it is in collapsed view before dragging
		var tmpID = obj.id.match(/_(\d+)$/);
		var mID = obj.parentNode.getAttribute("ModuleID");
		TV(null, mID, tmpID[1], null, true);
	}	
}

function SortDragEnd(obj)
{
	document.onselectstart = null;
}

// See if the javascript popup window actually opened or not
function CheckOpenWindow(openWin)
{
    var exists = false;
    if (openWin && !openWin.closed)
    {
        exists = true;
        try 
        {
            openWin.focus();
        }
        catch (e) 
        {
            exists = false;
        }
    }

    return exists; 
}

// Handle the User Choice Icons (ie. Favorite, Print, etc)
function CI(val, obj)
{
	// Get the main Document Node we're contained within
	var docNode  = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
	var itemID   = docNode.id.split("_")[1];
	var moduleID = docNode.parentNode.getAttribute("ModuleID");
	var url    = '/DesktopModules/Cool_News/NewsView.aspx?tabID=0&ItemID='+itemID+'&mid='+moduleID+'&wversion=Staging';
	
	if (docNode)
	{
		switch(val)
		{
			case 1: // Favorite
					break;
			case 2: // Print
			case 4: // New Window
					var scrX = parseInt(screen.width / 2) - 300;
					var scrY = parseInt(screen.height / 2) - 300;

					url = url + (val == 2 ? "&type=print" : "");
					var newWin = window.open(url,'printWin','width=600,height=600,resizable=1,scrollbars=1'+(val == 4 ? ',toolbar=1,location=1,status=1' : '')+',menubar=1,left='+scrX+',top='+scrY);
					if (!CheckOpenWindow(newWin))
						location.href = url;					
					break;		
			case 3: // Mail
					var title = document.getElementById("Title_"+moduleID+","+itemID).innerHTML;
					location.href="mailto:?subject="+title+" @ "+location.hostname+"&body=For more information check out:%0Ahttp://"+location.hostname + escape(url);
					break;		
		}
	}	
}
