﻿// SETTINGS:
var dropZoneClass = "dropZone";                         // Drop zone class.
var dropZoneOverBorderStyle = '1px dashed #333';        // On drop zone over.
var dropZoneVisibleBorderStyle = '1px dashed #333';     // On drop zone visible.
var dropHiddenBorderStyle = '1px dashed transparent';   // On drop zone visible.

// DO NOT CHANGE:
// ==============================================================================
var isIE = document.all;

var currentDragged;             // Current dragged object.
var currentDraggedStyle;

var currentDropZone;            // The current drop zone object.
var dropZoneArray = Array();    // Drop Zone Array.
var coord;

var oldZIndex;

// When document is loaded.
$(document).ready(function() {

    // Init all drop zones on the page.
    InitDropZones();

    // On mouse move event. Calculate the mouse position.
    document.onmousemove = getMouse;
});
// ==============================================================================

var save = false;

function RemoveElement(id) {
    var element = $("#" + id);
    if (element)
        element.remove();
}

/* Makes an element draggable */
function MakeDraggable(id) {
    currentDraggedStyle = document.getElementById(id).style;

    $("#" + id).draggable({
        helper: 'clone',
        cursor: 'move',
        opacity: .7,

        start: function(event, ui) {
            // Init current dragged element.
            currentDragged = document.getElementById(id);
            oldZIndex = currentDragged.style.zIndex;

            $(ui.helper).width($("#" + id).width());

            // Show all drop zones.
            ShowDropZones();
        },

        drag: function(event, ui) {

            // Get the active drop zone.
            //GetActiveDropZone();
        },

        stop: function(event, ui) {

            GetActiveDropZone();
            var child = GetActiveDropZoneElement();
            if (child) {
                if (child.id != currentDragged.id) {
                    var pos = getPosition(child);
                    if (coord.y < pos.y) {
                        child.parentNode.insertBefore(currentDragged, child);
                        //                        currentDropZone.insertBefore(currentDragged, child);
                    }
                    else if (coord.y > (pos.y + child.clientHeight)) {
                        child.parentNode.insertBefore(currentDragged, child.nextSibling);
                        //currentDropZone.insertBefore(currentDragged, child.nextSibling);
                    }
                    else if (coord.y < (pos.y + (child.clientHeight / 2))) {
                        child.parentNode.insertBefore(currentDragged, child);
                        //currentDropZone.insertBefore(currentDragged, child);
                    }
                    else if (coord.y > (pos.y + (child.clientHeight / 2))) {
                        child.parentNode.insertBefore(currentDragged, child.nextSibling);
                        //currentDropZone.insertBefore(currentDragged, child.nextSibling);
                    }
                }
            }
            else {
                if (currentDropZone)
                    currentDropZone.appendChild(currentDragged)
            }

            // Hide all drop zones.
            HideDropZones();

            $(this).draggable('destroy');

            save = true;
        }
    });
}


/* DROP ZONES FUNCTIONS */
function ShowDropZones() {
    // If the drop zone array is set.
    if (dropZoneArray) {
        for (i = 0; i < dropZoneArray.length; i++) {
            dropZoneArray[i].style.border = dropZoneVisibleBorderStyle;
            dropZoneArray[i].style.background = '#ddd';
        }
    }
}

function HideDropZones() {
    // If the drop zone array is set.
    if (dropZoneArray) {
        for (i = 0; i < dropZoneArray.length; i++) {
            dropZoneArray[i].style.border = dropHiddenBorderStyle;
            dropZoneArray[i].style.background = '';
        }
    }
}

/* Gets the active drop zone (when dragged element is over the drop zone) */
function GetActiveDropZone(event) {

    InitDropZones();    
    // If the drop zone array is set.
    if (dropZoneArray) {
        for (i = 0; i < dropZoneArray.length; i++) {
            var coord2 = getPosition(dropZoneArray[i]);
            if ((coord.x > coord2.x && coord.x < coord2.x + dropZoneArray[i].clientWidth) && (coord.y > coord2.y && coord.y < coord2.y + dropZoneArray[i].clientHeight)) {
                // Set the current drop zone.
                currentDropZone = dropZoneArray[i];

                // Set over class.
                currentDropZone.style.border = dropZoneOverBorderStyle;

                // Return the drop zone object.
                return currentDropZone;
            }
        }
    }

    if (currentDropZone) {
        currentDropZone.style.border = dropZoneVisibleBorderStyle;
    }
    
    // Set the current drop zone to nothing.
    currentDropZone = null;
    return null;
}

/* Gets the active element of the current drop zone */
function GetActiveDropZoneElement() {
    if (currentDropZone) {
        var children = getElementsByClassName("GadgetContainer", currentDropZone);
        if (children) {
            var childCoord;
            var lastGadget;
            var index = -1;
            for (a = 0; a < children.length; a++) {
                if (children[a].id == currentDragged.id) {
                    index = a;
                    break;
                }
            }

            if (index != -1)
                children.splice(index, 1);

            children.reverse();

            for (i = 0; i < children.length; i++) {
                childCoord = getPosition(children[i]);
                lastGadget = children[i];
                
                if(childCoord.y > coord.y){
                    if (i != 0)
                        return children[i - 1];
                    else
                        break;
                }              
            }

            if (lastGadget)
                return lastGadget;                
        }
    }
            
    // No children active;
    return null;
}

function InitDropZones() {
    // Get all elements that contain the drop zone class.
    dropZoneArray = getElementsByClassName(dropZoneClass, document.body);
}


/* GENERAL FUNCTIONS */

/* Gets elements by class name */
function getElementsByClassName(name, parent) {
    for (var o = [], n = new RegExp("\\b" + name.replace(/([(){}|*+?.,^$\[\]\\])/g, "\\\$1") + "\\b"), l = (parent || document).getElementsByTagName("*"), i = l.length; i--; )
        n.test(l[i].className) && (o[o.length] = l[i]);
    return o;
}

/* Gets the position of an element */
function getPosition(e) {
    var left = 0;
    var top = 0;

    try {
        if (e.offsetParent != null) {
            while (e.offsetParent) {
                left += e.offsetLeft;
                top += e.offsetTop;
                e = e.offsetParent;
            }
        }
    }
    catch (ex) {
        InitDropZones();
    }  

    left += e.offsetLeft;
    top += e.offsetTop;

    return { x: left, y: top };
}

function getDimensions(e) {
    var h = 0;  // hight
    var w = 0;  // width

    while (e.offsetParent) {
        e = e.offsetParent;
    }

    return { height: h, width: w };
}

/* Gets mouse position */
function getMouse(e) {
    if (!e) e = window.event;
    if (e && document.body) {
        coord = {
        x: isIE ? (e.clientX + document.documentElement.scrollLeft) : e.pageX,
        y: isIE ? (e.clientY + document.documentElement.scrollTop) : e.pageY

        };
    }
    
    if (save) {
        // Save
        SaveLayout();
        save = false;
    }
}

function SaveLayout() {
    if (currentDropZone) {

        var gadgets;
        var message = "data=[";
        for (i = 0; i < dropZoneArray.length; i++) {
            gadgets = getElementsByClassName("GadgetContainer", dropZoneArray[i]);       

            var item;
            for (a = 0; a < gadgets.length; a++) {
                message += "id=" + gadgets[a].id + "|position=" + "|order=" + (a + 1) + "|container=" + dropZoneArray[i].id + ";";
            }
        }
        message += "]";

        try {
            ajaxObject = GetXmlHttpObject();
            ajaxObject.open("POST", "Core/Scripts/SaveGadgets.aspx", true);
            ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            ajaxObject.setRequestHeader("Content-length", message.length);
            ajaxObject.setRequestHeader("Connection", "close");
            ajaxObject.send(message);
        }
        catch (ex) {
        }  
    }
}

function GetXmlHttpObject() {
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        var xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
            }
        }
    }
    return xmlHttp;
}

function LoadExternalPageContent(element, url, height) {
    var obj = document.getElementById(element);
    obj.innerHTML = "<iframe src=\"" + url + "\" width=\"100%\" height=\"" + height + "\"></iframe>";
}


function OpenDialog(id, arguments)
{
    var controlId = "#" + id;
    $(controlId).dialog(arguments);
    $(controlId).parent().appendTo($("form:first"));            
    $(controlId + '.ui-dialog-titlebar-close').show();
    $(controlId).dialog('open');
}

function OpenEditDialog(id, arguments)
{
    var controlId = "#" + id;
    var parent = $(controlId).parent();
    var s = $(controlId).attr('style');
    var c = $(controlId).attr('class');
    
    $(controlId).dialog(arguments);
    $(controlId).bind('dialogclose', function(event, ui) {
      $(controlId).attr('style', '');
      $(controlId).attr('class', '');              
      $(controlId).attr('style', s);
      $(controlId).attr('class', c);
      $(controlId).appendTo(parent);
      $(controlId).destroy();
    });

    $(controlId).parent().appendTo($("form:first"));            
    $(controlId).dialog('open');
}

function CycleImages(id) {
    $("#" + id).ready(function() {
        $("#" + id).cycle({
            fx: 'fade',
            speed: 1000,
            timeout: 8000
        });
        $("#" + id).show();
    });
}

function GoogleAnalytics() {
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

    try {
    var pageTracker = _gat._getTracker("UA-15582769-1");
    pageTracker._setDomainName(".hydrologic.nl");
    pageTracker._trackPageview();
    } catch(err) {}
}