// querystring function from eggheadcafe
function PageQuery(q) {
	if (q.length > 1) { this.q = q.substring(1, q.length); }
	else { this.q = null; }

	this.keyValuePairs = new Array();
	if (q) {
		for (var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}

	this.getKeyValuePairs = function() { return this.keyValuePairs; }

	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if (this.keyValuePairs[j].split("=")[0] == s) {
				return this.keyValuePairs[j].split("=")[1];
			}
		}
		return false;
	}

	this.getParameters = function() {
		var a = new Array(this.getLength());

		for	(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}

	this.getLength = function() { return this.keyValuePairs.length; }
}

function queryString(key){
	var page = new PageQuery(window.location.search);
	return unescape(page.getValue(key));
}

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;
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name)
{
    if (getCookie(name))
    {
        document.cookie = name + "=;path=/admin/";
    }
}

function resetCookie(name, lookFor, lookFor2, replaceWith)
{
    var cookie = getCookie(name);
    deleteCookie(name);

    cookie = cookie.replace(lookFor, "*");
    cookie = cookie.replace(lookFor2, "*");
    cookie = cookie.replace("*", replaceWith);
    
    document.cookie = name+"="+cookie+";path=/admin/";
}

function initialize()
{
    init();
}

function init()
{
	var menu = document.getElementById("hideMe");
	var o = document.getElementById("useMe");

	var cookie = getCookie("LHM");

	if (cookie != null && cookie != "")
	{
		toggleSideMenu(cookie, menu, o);
	} else {
	    deleteCookie("LHM");
		document.cookie = "LHM=main:0|published_site:1|site_members:1|site_assets:1|modules:1;path=/admin/";
		toggleSideMenu(".....0", menu, o);
	}
	
	resetMenu();
	
	cookie = getCookie("LHM");
	var children = cookie.split("|");
	for (var i=1; i<children.length; i++)
	{
	    var obj = children[i].substring(0, children[i].length - 2);
	    var toggle = children[i].replace(obj+":", "");
	    
	    if (toggle == 1)
	    {
	        document.getElementById(obj).style.display = 'none';
	        document.getElementById(obj+"img").src = "/admin/common/images/expand.gif";
	    } else {
	        document.getElementById(obj).style.display = '';
	        document.getElementById(obj+"img").src = "/admin/common/images/contract.gif";
	    }
	}
}

function resetMenu()
{
    var url = window.location.href;
    var cookie = getCookie("LHM");
    
    var newCookie = "LHM="+cookie.substring(0,7);
    newCookie += "published_site:1|site_members:1|site_assets:1|modules:1;path=/admin/";
    
    if (url.indexOf("modules.aspx") > -1) { newCookie = newCookie.replace("modules:1", "modules:0"); }
    else if (url.indexOf("/pages/") > -1) { newCookie = newCookie.replace("published_site:1", "published_site:0"); }
    else if (url.indexOf("/subscribers/") > -1) { newCookie = newCookie.replace("site_members:1", "site_members:0"); }
    else if (url.indexOf("/articles") > -1 || url.indexOf("/Calendar") > -1 
        || url.indexOf("/definitions") > -1 || url.indexOf("/ECommerce") > -1
        || url.indexOf("/faq") > -1 || url.indexOf("/Gallery") > -1
        || url.indexOf("/newsletter") > -1) { newCookie = newCookie.replace("modules:1", "modules:0"); }
    else if (url.indexOf("/assets/") > -1) { newCookie = newCookie.replace("site_assets:1", "site_assets:0"); }

    deleteCookie("LHM");
    document.cookie = newCookie;
}

function toggleSideMenu(hidden, menu, o)
{
    var main = hidden.substring(5,6);
	if (main == "1")
	{
		o.src = "/admin/common/images/slideout.gif"
		menu.style.display = "none";
	} else {
		o.src = "/admin/common/images/slidein.gif";
		menu.style.display = "";
	}
}

function hideSideMenu()
{
	var menu = document.getElementById("hideMe");
	var o = document.getElementById("useMe");

	if (o.src.indexOf("slidein.gif") > -1)
	{
	    resetCookie("LHM", "main:0", "main:1", "main:1");
		toggleSideMenu(".....1", menu, o);
	} else if (o.src.indexOf("slideout.gif") > -1)
	{
	    resetCookie("LHM", "main:0", "main:1", "main:0");
		toggleSideMenu(".....0", menu, o);
	} else { alert('site menu image isnt right'); }
}

function toggleLHM(img, obj)
{
	if (document.getElementById(obj).style.display=='none' ){
		document.getElementById(obj).style.display = '';
		resetCookie("LHM", obj+":0", obj+":1", obj+":0");
	} else{
		document.getElementById(obj).style.display = 'none';
		resetCookie("LHM", obj+":0", obj+":1", obj+":1");
	}
	
	if (img.src.indexOf("expand.gif") > -1)
	{
	    img.src = "/admin/common/images/contract.gif";
	} else { img.src = "/admin/common/images/expand.gif"; }
}

function highlight(o, toggle, color)
{
	if (toggle)
	{
		o.style.border = "1px dashed "+color;
	}
	else
	{
		o.style.border = "";
	}
}

function showError(err)
{
	alert(err);
}

function showDescription(desc)
{
	var o = document.getElementById("description");
	o.innerHTML = desc;
	o.style.color = "red";
}

function showDefinition(o, definition)
{
    var children = o.childNodes;
    if (children.length > 1) {
	    for (var i=1; i<children.length; i++)
	    { 
	        o.removeChild(children[i]); 
        }
    }
    else {
	    var x = findPosX(o);
	    var y = findPosY(o)-20;

	    if (x && y)
	    {
		    var div = document.createElement("div");
		    div.style.top = y+"px"; div.style.left = x+"px";
		    div.className = "r_definition_popup";
		    div.style.position = "absolute";
		    div.innerHTML = "&nbsp;"+definition;
		    
		    o.appendChild(div);
	    }
    }
}

function centerScreen(width, height)
{
	return "top="+((screen.height - height)/2)+",left="+((screen.width - width)/2);
}

function options(width, height)
{
    return "toolbar=0,width="+width+", height="+height+", scrollbars=1,"+centerScreen(width, height);
}

function editContent(contentId, frontEnd, clientID)
{
    if (!frontEnd)
    {
        var url = "/admin/pages/editcontent.aspx?ContentId="+contentId+"&FrontEnd="+frontEnd;
        var frame = "<iframe frameborder=0 id=\"editcontentframe\" name=\"editcontentframe\" width=\"100%\" height=\"360px\" src=\""+url+"\" scrolling=\"auto\" ></iframe>";
    
        clientID.innerHTML = frame;
    }
    else
    {
    	var url = "/admin/pages/editcontent.aspx?ContentId="+contentId+"&FrontEnd="+frontEnd;
	    customPopup(url, 580, 480, "Edit Content");
    }
}

function editControl(pageId, control, controlId)
{
	var url = "/admin/pages/editcontrol.aspx?PageId="+pageId;
	url += "&Control="+control+"&ControlId="+controlId;
	
	//window.open(url, 'test', options(440, 300));
	customPopup(url, 440, 300, "Edit Control");
}

function editControlFromBackend(controlId, control)
{
	var url = "/admin/pages/editcontrol.aspx?ControlId="+controlId;
	url += "&Control="+control;
	
	//window.open(url, 'test', options(440, 300));
	customPopup(url, 440, 300, "Edit Control");
}

var passbackTo = null;

function rowSelected(value)
{
    var o = document.getElementById(passbackTo);
    if (o == null || o == 'undefined')
    {
        var items = document.getElementsByTagName("*");
        for (var i=0; i<items.length; i++)
        {
            var element = items[i].id.replace(/^\s*|\s*$/g,"");
            passbackTo = passbackTo.replace(/^\s*|\s*$/g,"");
            if (element.indexOf(passbackTo) > -1) { o = items[i]; }
        }
    }
    
	o.value = value;
}

function popSelect(returnTo, url, width, height)
{
	passbackTo = returnTo;
	window.open(url, newGuid(), options(width, height));
	return false;
}

function newGuid()
{
	var out = '';
	var hex = new Array('0','1','2','3','4','5','6','7','8', '9','a','b','c','d','e','f');
			
	for (count = 0; count < 32; count++)
	{					
		out += hex[Math.floor(Math.random() * 16)];
	}
	return out;
}

function pop(url, width, height, title, parentiframeID)
{
	customPopup(url, width, height, title, parentiframeID);
	//window.open(url, newGuid(), options(width, height));
}

function popUpgrade(url)
{
    customPopup(url, 350, 200, "Upgrade Magnetize");
    //window.open(url, newGuid(), "toolbar=0,width=350, height=200, scrollbars=1");
}

function renderPageFromCaller()
{
    //var frame = caller.document || caller.contentWindow.document;
    var controls = document.getElementById("customPopupDiv").getElementsByTagName("IFRAME");
    for (var i=0; i<controls.length; i++)
    {
        var f = document.getElementById(controls[i].getAttribute('piframe'));
        /*if (f.contentDocument)
        {
            alert('ok cd');
            f.contentDocument.localRenderPage();
        }
        else if (f.contentWindow)
        {
            //f.contentWindow.document.localRenderPage();
        }*/
        f = f.contentWindow || f.contentDocument;
        f.localRenderPage();
        //frame.localRenderPage();
    }
}

function customPopup(url, width, height, title, parentiframeID)
{
    var frame = "<iframe frameborder=0 name=\"customPopupFrame\" width="+(width)+" height="+(height+30)+" src=\""+url+"\" scrolling=\"auto\" piframe=\""+parentiframeID+"\"></iframe>";
   
    document.getElementById("customPopupDiv").style.top = (((screen.height - height)/2)-100) + ((document.all)?document.body.scrollTop:window.pageYOffset) + "px";
    document.getElementById("customPopupDiv").style.left = ((screen.width - width)/2) + "px";
    document.getElementById("customPopupDiv").style.visibility="visible";
    Drag.init(document.getElementById("customPopupDiv"));
    
    var toolbar = "<table width=\""+width+"\" height=\""+(height+50)
                    +"\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\" style=\"border: solid 1px black; background-color: white;\">";
        toolbar += "<tr style=\"background-image: url('/admin/common/images/grid/title_bk.gif'); height: 20px; cursor: move;\"><td style=\"width: "+(width-30)+"px; padding-left: 5px; color: white; font-weight: bold;\">"+title+"</td>";
        toolbar += "<td><img src=\"/admin/common/images/delete2.gif\" onclick=\"closeCustomPopup();\" style=\"cursor: pointer;\" /></td></tr>";
        toolbar += "<tr><td colspan=\"2\">"+frame+"</td></tr>";
        toolbar += "<tr style=\"background-image: url('/admin/common/images/grid/bar_bk.gif'); background-repeat: repeat-x; background-position: bottom; height: 20px;\"><td colspan=\"2\" style=\"height: 20px;\" align=\"right\" valign=\"bottom\"><img src=\"/admin/common/images/grid/resize.gif\" /></td></tr>";
        toolbar += "</table>";
    
    document.getElementById("customPopupDiv").innerHTML = toolbar;   
}

function closeCustomPopup()
{
    document.getElementById("customPopupDiv").innerHTML = "";
    document.getElementById("customPopupDiv").style.visibility="hidden";
}

function logout()
{
    document.getElementById("ctl00_logout").click();
}

function redirect(url)
{
	window.location.href = url;
}

function reindex()
{
    document.getElementById("siteindeximg").innerHTML = "<br /><img src=\"/admin/common/images/animated_loading.gif\" />&nbsp;<font color=\"green\">please wait...</font>";
    Admin_SiteSettings.ReIndexSite(reindex_callback);
    return false;
}

function reindex_callback(res)
{
    if (res != null && res.value != null)
    {
        window.location.href=window.location.href;
    }
}

function findControl(id)
{
    return;
}

function toggleError(img, id)
{
    if (img.src.indexOf("expand.gif") > -1)
    {
        document.getElementById(id).style.display = '';
        img.src = "/admin/common/images/contract.gif";
    } else {
        document.getElementById(id).style.display = 'none';
        img.src = "/admin/common/images/expand.gif";
    }
}

var detail = null;
function floatInformation(control, details, e)
{
    detail = document.getElementById(control);
    if (detail && detail.style.visibility == "hidden")
    {
        detail.style.left = e.pageX ? pageXOffset + e.clientX + 20 : document.body.scrollLeft + e.x + 20;
        detail.style.top = e.pageY ? pageYOffset + e.clientY : document.body.scrollTop  + e.y;
        detail.style.visibility = "visible";
        detail.innerHTML = details;
    } else { closeInformation(); }

    return false;
}

function closeInformation()
{
    if (detail) { detail.style.visibility = "hidden"; }
}

// context menu
var clickedOnType = "";
var clickedOnID = "";
var clickedOnTitle = "";

var ie5 = document.all && document.getElementById;
var ns6 = document.getElementById && !document.all;

function attachContextMenu(menuID)
{
    var menu;
    if (ie5 || ns6) { menu = document.getElementById(menuID); }
    
    return menu;
}

function showContextMenu(menuID, clickedOn, coT, coID, coTitle)
{
    clickedOnType = coT;
    clickedOnID = coID;
    clickedOnTitle = coTitle;
    
    var menu = attachContextMenu(menuID);
    var posX = findPosX(clickedOn) + 20;
    var posY = findPosY(clickedOn) + 20;
    
    menu.style.left = posX+"px";
    menu.style.top = posY+"px";
    menu.className = "contextMenu";
    
    setTimeout("hideContextMenu('"+menuID+"')", 5000);
    
    return false;
}

function hideContextMenu(menuID)
{
    var menu = attachContextMenu(menuID);
    menu.className = "contextMenu contextMenuHidden";
}

function contextMenuAction(menuID, action)
{
    hideContextMenu(menuID);
    
    switch (action)
    {
        case "EDIT":
            if (clickedOnType == "PAGE") {
                if (window.location.href.indexOf("/pages/manage.aspx") == -1)
                {
                    window.location.href="/admin/pages/manage.aspx?PageId="+clickedOnID+"&PageTitle="+clickedOnTitle; 
                } else {
                    addTab(clickedOnTitle, clickedOnID);
                }
            }
            break;
        case "DELETE":
            if (clickedOnType == "PAGE") { deletePageFromContextMenu(clickedOnID); }
            break;
        case "PUBLISH":
            if (clickedOnType == "PAGE") { quickPublishPage(clickedOnID); }
            break;
        case "TAKEOFFLINE":
            if (clickedOnType == "PAGE") { takePageOffline(clickedOnID); }
            break;
        case "DUPLICATE":
            if (clickedOnType == "PAGE") { window.location.href="/admin/pages/addpage.aspx?DuplicateFrom="+clickedOnID; }
            break;
        default:
            break;
    }
    
    return false;
}

function deletePageFromContextMenu(id)
{
    if (confirm('are you sure you want to delete this page?'))
    {
        Magnetism.Magnetize.Web.Common.DeletePage(id, deletePageFromContextMenu_callback);
    }
    return false;
}

function deletePageFromContextMenu_callback(res)
{
    if (res != null)
    {
        if (res.value) { window.location.href="/admin/pages/addpage.aspx"; }
        else { alert('unable to delete that page.'); }
    }
}

function quickPublishPage(id)
{
    Magnetism.Magnetize.Web.Common.QuickPublish(id, quickPublishPage_callback);
    return false;
}

function quickPublishPage_callback(res)
{
    if (res != null)
    {
        if (res.value) { window.location.href=window.location.href; }
        else { alert('unable to publish that page.'); }
    }
}

function takePageOffline(id)
{
    Magnetism.Magnetize.Web.Common.TakeOffline(id, takePageOffline_callback);
    return false;
}

function takePageOffline_callback(res)
{
    if (res != null)
    {
        if (res.value) { window.location.href=window.location.href; }
        else { alert('unable to take that page offline.'); }
    }
}

var thumb = null;
function viewGalleryImage(image, e)
{
    thumb = document.getElementById("thumbnail");
    if (thumb && thumb.style.visibility == "hidden")
    {
        thumb.style.left = e.pageX ? pageXOffset + e.clientX + 20+"px" : document.body.scrollLeft + e.x + 20+"px";
        thumb.style.top = e.pageY ? pageYOffset + e.clientY + 20+"px" : document.body.scrollTop  + e.y + 20+"px";
        thumb.style.visibility = "visible";
        thumb.innerHTML = "<img src=\"" + image + "\">";
    } else { closeThumbnail(); }

    return false;
}

function closeThumbnail()
{
    if (thumb) { thumb.style.visibility = "hidden"; }
}

    function fixTreeView()
    {      
        var treeCookie = getCookie("TreeView");
        if (treeCookie != null && treeCookie != "")
        {
            hookIntoTree(false);
        }
        else
        {
            hookIntoTree(true);
        }
    }
    
    function hookIntoTree(saveCookie)
    {
        var cookie = "TreeView=";
        var tree = document.getElementById("ctl00_pagelist");
        
        if (tree != null)
        {
            var togglable = tree.getElementsByTagName("a");
            for (var i=0; i<togglable.length; i++)
            {
                if (togglable[i].href.indexOf("TreeView_ToggleNode") > -1)
                {
                    togglable[i].href = togglable[i].href.replace("TreeView_ToggleNode", "CustomTreeView_ToggleNode");
                    
                    var params = togglable[i].href.split(",");
                    var children = eval(params[4].substring(0, params[4].length - 1));
                    var data = eval(params[0].substring(params[0].indexOf("(")+1));
                    var index = params[1];
                    var node = eval(params[2]);
                    var lineType = params[3];
                    
                    cookie += togglable[i].id
                            +":"+children.style.display+"|";
                    
                    if (!saveCookie)
                    {
                        cookie = getCookie("TreeView");
                        params = cookie.split("|");
                        
                        for (var j=0; j<params.length; j++)
                        {
                            if (params[j].indexOf(togglable[i].id) > -1)
                            {
                                var display = params[j].substring(params[j].indexOf(":") + 1).replace("|", "");
                                if (children.style.display != display)
                                {
                                    CustomTreeView_ToggleNode(data, index, node,lineType, children);
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
        
        cookie = cookie + ";path=/admin/";
        if (saveCookie) { document.cookie = cookie; }
    }
    
    function saveState(id, onoff)
    {
        var cookie = getCookie("TreeView");
        if (cookie.indexOf(id) > -1)
        {
            cookie = cookie.replace(id+":none", id+":*").replace(id+":block", id+":*");
            cookie = cookie.replace(id+":*", id+":"+onoff);
        }
        document.cookie = "TreeView="+cookie+";path=/admin/";
    }
    
    function CustomTreeView_ToggleNode(data, index, node, lineType, children) {
    var img = node.childNodes[0];
    var newExpandState;
    try {
        if (children.style.display == "none") {
            children.style.display = "block";
            newExpandState = "e";
            if ((typeof(img) != "undefined") && (img != null)) {
                if (lineType == "l") {
                    img.src = data.images[15];
                }
                else if (lineType == "t") {
                    img.src = data.images[12];
                }
                else if (lineType == "-") {
                    img.src = data.images[18];
                }
                else {
                    img.src = data.images[5];
                }
                img.alt = data.collapseToolTip.replace(/\{0\}/, TreeView_GetNodeText(node));
                
                saveState(node.id, "block");
            }
        }
        else {
            children.style.display = "none";
            newExpandState = "c";
            if ((typeof(img) != "undefined") && (img != null)) {
                if (lineType == "l") {
                    img.src = data.images[14];
                }
                else if (lineType == "t") {
                    img.src = data.images[11];
                }
                else if (lineType == "-") {
                    img.src = data.images[17];
                }
                else {
                    img.src = data.images[4];
                }
                img.alt = data.expandToolTip.replace(/\{0\}/, TreeView_GetNodeText(node));
                
                saveState(node.id, "none");
            }
        }
    }
    catch(e) {}
    data.expandState.value =  data.expandState.value.substring(0, index) + newExpandState + data.expandState.value.slice(index + 1);
}

function toggleProgress(id, hide)
{
    if (!hide)
    {
        document.getElementById(id).innerHTML = "<img src=\"/admin/common/images/animated_loading.gif\" />&nbsp;<font color=\"green\">loading, please wait...</font>";
        document.getElementById(id).style.display = '';
    } else { document.getElementById(id).style.display = "none"; }
}