﻿var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;
var zoneChildNodesCount = 0;
var clickElParent;

YAHOO.example.DDApp = 
{
    init: function() 
    {
        //Add registration of any objects when u need
    }
};
function ShowHideWebPart(webPartId)
{
    var webPart = document.getElementById(webPartId);
    if(webPart.style.display == '' || webPart.style.display == 'block')
    {
        webPart.style.display = 'none';
        webPart.attributes['IsClosed'].value = true;
    }
    else 
    {
        webPart.style.display = 'block';
        webPart.attributes['IsClosed'].value = false;
    }
    
    SavePageSettings();
    
}
function ShowWebPartMenu(webPartMenuButtonId,menuDivId)
{
    var coors = Dom.getXY(webPartMenuButtonId);
	var menuDiv = document.getElementById(menuDivId);
	coors[1] += 15; //Top container Padding
	coors[0] -= 160; //Menu with to be right aligned
	menuDiv.style.top = coors[1]  + 'px';
	menuDiv.style.left = coors[0] + 'px';
	menuDiv.style.display = 'block';
}

function ShowWebPartTabMenu(webPartMenuButtonId,menuDivId)
{
    var coors = Dom.getXY(webPartMenuButtonId);
	var menuDiv = document.getElementById(menuDivId);
	coors[1] += 38; //Top container Padding
	coors[0] -= 165; //Menu with to be right aligned
	menuDiv.style.top = coors[1]  + 'px';
	menuDiv.style.left = coors[0] + 'px';
	menuDiv.style.display = 'block';
}

function ShowElementWithShift(webPartMenuButtonId,menuDivId,topShift,leftShift)
{    
    var coors = Dom.getXY(webPartMenuButtonId);
	var menuDiv = document.getElementById(menuDivId);
	menuDiv.style.opacity = 1;
	menuDiv.style.filter = 'alpha(opacity:100)';
	coors[1] += topShift; //Top container Padding
	coors[0] += leftShift; //Menu with to be right aligned
	menuDiv.style.top = coors[1]  + 'px';
	menuDiv.style.left = coors[0] + 'px';
	menuDiv.style.display = 'block';
	clearTimeout(t1);
}

function ShowWebPartTabMenuFireFox(webPartMenuButtonId,menuDivId)
{
    var coors = Dom.getXY(webPartMenuButtonId);
	var menuDiv = document.getElementById(menuDivId);
	coors[1] += 38; //Top container Padding
	coors[0] -= 125; //Menu with to be right aligned
	menuDiv.style.top = coors[1]  + 'px';
	menuDiv.style.left = coors[0] + 'px';
	menuDiv.style.display = 'block';
}

function MoveWebPart(e, target,state,isClosed)	
{
    var srcEl = document.getElementById(e);
    if(srcEl != null )
    {
        if(target != '')
        {
            var destZone = document.getElementById(target);
            destZone.appendChild(srcEl);
        }
        var contents = document.getElementById(e.replace('_webPart','_main_contents_table'));
        var minIcon = document.getElementById(e.replace('_webPart','_MinMaxIconId')); 
        if(state == 'Minimized')
        {
            Dom.setStyle(contents, "opacity", 0); 
            var hide = new YAHOO.util.Anim(e, { height: { to: 25 } }, 0.0000001, YAHOO.util.Easing.easeNone);
            hide.onComplete.subscribe(function(){ Dom.setStyle(contents, "display", 'none'); });
            hide.animate();
            
            minIcon.src = minIcon.src.replace('MinIcon','RestoreIcon');
        }
        if(isClosed)
        {
            srcEl.style.display = 'none';
            srcEl.attributes['IsClosed'].value = true;
        }
    }   
}

function RemoveWebPart(webPartId,docNodeParentId,showConfirm)
{
    if(showConfirm == 'true') 
    {
        if(confirm('Are you sure you want to delete this web part?'))
        {
            DeleteWebPart(webPartId,docNodeParentId);
        }
    }
    else 
    {
        DeleteWebPart(webPartId,docNodeParentId);
    }
}
function DeleteWebPart(webPartId,docNodeParentId)
{
     var webPart = document.getElementById(webPartId);
     var flashPanelViewerId=webPartId.replace("webPart","flashPanelViewer");
     var flashPanelEditorId=webPartId.replace("webPart","flashPanelEditor");
     var flashPanelViewer=document.getElementById(flashPanelViewerId);
     var flashPanelEditor=document.getElementById(flashPanelEditorId);
     if(flashPanelViewer !=null && flashPanelEditor !=null)
     {
        flashPanelViewer.style.display='none';
        flashPanelEditor.style.display='none';
     }
     
          var hideAttributes = { height: { to: 0 } , opacity: {to:0} };
 var hide = new YAHOO.util.Anim(webPartId, hideAttributes, 1, YAHOO.util.Easing.backIn);
 hide.animate();
 hide.onComplete.subscribe(function(){ Dom.setStyle(webPartId, 'display','none') } );
 //Delete web part data from the database.
 DeleteDocNodeChildNodes(docNodeParentId);


}
function getAllWebPartsId()
{
    var webPartsId='';
    var webParts = Dom.getElementsBy(function(el) {if (el.id.indexOf('webPart') > 0 ) return true; else return false; },'div');
    for(i=0; i < webParts.length ; i++)
    {
        if(webParts[i].parentNode.id != '' && webParts[i].parentNode.id.indexOf('zone') != -1)
        {
            webPartsId+=webParts[i].id+'&'; 
        }
    }
    return webPartsId;
}

function getAllWebParts()
{
    
    var webParts = Dom.getElementsBy(function(el) {if (el.id.indexOf('webPart') > 0 ) return true; else return false; },'div');
    var args ='';
    
    for(i=0; i < webParts.length ; i++)
    {
        var title = document.getElementById(webParts[i].id.replace('_webPart','_SmartWebPartTitleBarText'));
        var titleText = '';
        if(title != null) 
        {
            titleText = title.innerHTML;
        }
        else 
        {
            titleText = 'Untitled';
        }
        if(webParts[i].attributes['WebPartGroup']!= null)
        {
            if(webParts[i].parentNode.id != '' && webParts[i].parentNode.id.indexOf('zone') != -1)
            {
                args += webParts[i].id  + '~!~' 
                + webParts[i].parentNode.id + '~!~' 
                + webParts[i].clientHeight + '~!~' 
                + webParts[i].attributes['WebPartGroup'].value + '~!~' 
                + webParts[i].attributes['IsClosed'].value + '~!~'
              //  + webParts[i].attributes['Key'].value + '~!~'
                + titleText.replace('&amp;','-') + '***';
            }
            else 
            {
                args += webParts[i].id  
                + '~!~NotInZone~!~' 
                + webParts[i].clientHeight 
                + '~!~' + webParts[i].attributes['WebPartGroup'].value + '~!~'
                + webParts[i].attributes['IsClosed'].value + '~!~'
             //   + webParts[i].attributes['Key'].value + '~!~'
                + titleText.replace('&amp;','-') + '***';
            }
        }   
    }
    
    return args;
}
//////////////////////////////////////////////////////////////////////////////
// custom drag and drop implementation
//////////////////////////////////////////////////////////////////////////////
YAHOO.example.DDList = function(id, sGroup, config) 
{
    YAHOO.example.DDList.superclass.constructor.call(this, id, sGroup, config);
    dragEl = this.getDragEl();   
    Dom.setStyle(dragEl, "opacity", 0.3); // The proxy is slightly transparent
    this.goingUp = false;
    this.lastY = 0;
};

YAHOO.extend(YAHOO.example.DDList, YAHOO.util.DDProxy, 
{
    startDrag: function(x, y) 
    {
        // make the proxy look like the source element
         var clickEl = this.getEl();
          Dom.setStyle(clickEl, "opacity", 0.67);
          var clonedClickEl = clickEl.cloneNode(true);
            var children = clonedClickEl.getElementsByTagName("*");
            for(var i = 0; i < children.length; i++)
            {
                children[i].id = '';
                
            } 
        dragEl.innerHTML = clonedClickEl.innerHTML;
        Dom.setStyle(dragEl, "border", "0px");
        
    },

    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(dragEl, "visibility", "");
        var a = new YAHOO.util.Motion( 
            dragEl, { 
                points: { 
                    to: Dom.getXY(srcEl)
                }
            }, 
            0.5, 
            YAHOO.util.Easing.easeIn
        )
       var thisid = this.id;
        // Hide the proxy and show the source element when finished with the animation
        a.onComplete.subscribe(function() 
            {
                Dom.setStyle(dragEl.id, "visibility", "hidden");
                Dom.setStyle(thisid, "visibility", "");
                Dom.setStyle(thisid, "opacity", "1");
            });
        a.animate();
        
    SavePageSettings();
    
    },

    onDragDrop: function(e, id) 
    {
        // If there is one drop interaction, the div was dropped either on the list,
        // or it was dropped on the current location of the source element.
        if (DDM.interactionInfo.drop.length === 1) 
        {
            // 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; 
            // Check to see if we are over the source element's location.  We will
            // append to the bottom of the list once we are sure it was a drop in
            // the negative space (the area of the list without any list items)
            if (!region.intersect(pt)) 
            {
                var destEl = Dom.get(id);
                var destDD = DDM.getDDById(id);
                destEl.appendChild(this.getEl());
                destDD.isEmpty = false;
                DDM.refreshCache();
            }
        }
    },

    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);     
       
            if (destEl.id.indexOf("webPart") != -1) 
            {
                var p = destEl.parentNode;
               
                if (this.goingUp) 
                {
                    p.insertBefore(srcEl, destEl); // insert above
                } 
                else 
                {
                    p.insertBefore(srcEl, destEl.nextSibling); // insert below
                }

                DDM.refreshCache();
            }
    }
});

Event.onDOMReady(YAHOO.example.DDApp.init, YAHOO.example.DDApp, true);

var request;
var response;
function InitializeRequest()
{
	try
	{
		request = new ActiveXObject("Microsoft.XMLHTTP");//Try creating an XMLHTTP Object		
	}
	catch(Ex)
	{
		try
		{
			request = new ActiveXObject("Microsoft.XMLHTTP");//First failure, try again creating an XMLHTTP Object
		}
		catch(Ex)
		{
			request = null;//Else assign null to request
		}
	}
	if(!request&&typeof XMLHttpRequest != 'undefined')
	{
		request = new XMLHttpRequest();
	}
}

function ProcessRequest()
{
    if(request.readyState == 4)//If the readyState is in the "Ready" state
	{
		if(request.status == 200)//If the returned status code was 200. Everything was OK.
	    {
		}
	}
	return true;//return
}

function DeleteDocNodeChildNodes(docNodeId)
{
    InitializeRequest();
    var url = "WebPartPersonalization.aspx?cmd=del&docNodeParentId="+docNodeId;
    request.onreadystatechange = ProcessRequest;
    request.open("GET", url, true);
    request.send(null);
    SavePageSettings();
}
function SavePageSettings()
{
    var date = new Date();
    InitializeRequest();
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    var args = getAllWebParts();
    args = args.replace('&nbsp;','');

    request.onreadystatechange = ProcessRequest;//Delegate ProcessRequest to onreadystatechange property so it gets called for every change in readyState value

    var url = "WebPartPersonalization.aspx";
    var param =  "cmd=SavePage&path="+sPage+"&args="+args+"&stamp="+date.getMilliseconds();
    
    request.open("POST", url, true);//Open a GET request to the URL
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", param.length);
    request.send(param);
}

function ApplyPersonalization()
{
    InitializeRequest();
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
//    var args = getAllWebParts();
    var url = "WebPartPersonalization.aspx?cmd=LoadPersonalization&path="+sPage;
    request.onreadystatechange = ProcessRequest;//Delegate ProcessRequest to onreadystatechange property so it gets called for every change in readyState value
    request.open("GET", url, true);//Open a GET request to the URL
    request.send(null);//Send the request with a null body.
}
function Highlight(pageUrl)
{
   window.location.href =unescape(window.location.pathname + "?Color=Pink#SignUpAnchor");
    
}
   