// Display the created right mac on screen
function showRyMacBox(id) {
    reposition(id);
    createOverlay(id);
    $("#" + id).show();
}

// Create a layer under the macbox
// User could click on this to close the form.
function createOverlay(id) {
    var overlayLayer = document.createElement("div");
    $(overlayLayer).attr("class", "macbox-overlay");
    $(overlayLayer).click(function() {
        hideRyMacBox(id);
    });
    $(overlayLayer).height($(document).height());
    $("body").append(overlayLayer);
}

// Center the macbox in the screen
// seem something not right here, need to take a look later
function reposition(id) {
    var thisEle = $("#" + id).get(0);
    if (thisEle == null) return;
    
    var sidePos = (($(window).width() / 2) - ($(thisEle).width() / 2));
    if (sidePos < 0) sidePos = 0;
    sidePos += "px";
    $(thisEle).css("left", sidePos);
    
    var topPos = $(window).scrollTop() + ($(window).height() / 2) - ($(thisEle).height() / 2);
    if (topPos < 0) topPos = 0;
    topPos += "px";
    $(thisEle).css("top", topPos);
}

function isdefined(variable) {
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function hideRyMacBox(id) {
    $("#" + id).hide();
    $(".macbox-overlay").remove();
    //see if we have anything to do on close
    if (macboxObjs["_" + id] != undefined) {
        macboxObjs["_" + id].oncloseFunc();
    }
}

function RyMacBox(name, image, width, height, outputToEle, attributesObj, forceHeight, callbackFunction, doOverlay, macboxStyle) {

	// Required //
	//////////////
	this.image = image;
	this.image.isHtml = false;
	this.output = $("body").get(0);
	this.name = name;
	this.callbackFunction = callbackFunction;
	this.doOverlay = doOverlay;
	
	this.style = "";
	if (macboxStyle != null) {
	    if (macboxStyle == "round") {
	        this.style = "-round";
	    }
	    else if (macboxStyle == "basic") {
	        this.style = "-basic";
	    }
	}

	this.width = width;	// Width in pixels
	this.height = height;	// Height in pixels
	this.forceHeight = forceHeight;

	if (typeof(this.image) != "object") {
		var bits = this.image.split("|");

		if ((bits[0] == "swf")||(bits[0] == "SWF")) {
			var src = bits[1];
	
			this.image = {};
			this.image.src = src;
			this.image.isFlash = true;
		}
		else if ((bits[0] == "html")||(bits[0] == "HTML")) {
			var DATA = document.getElementById(bits[1]).innerHTML;
			
			this.image = {};
			this.image.object = document.getElementById(bits[1]);
			this.image.data = DATA;
			this.image.origEle = document.getElementById(bits[1]);
			this.image.isFlash = false;		
			this.image.isHtml = true;
		}
		else if (bits[0].toLowerCase() == "img") {
		    var box = document.createElement("div");
		    $("body").append(box);
		    $(box).attr("id", bits[1]); 
		    var img = document.createElement("img");
		    $(box).append(img);
		    $(img).attr("src", attributesObj.image);
		    $(img).attr("rel", this.name);
		    $(img).bind("load", function() {
		        reposition($(this).attr("rel"));
            });
		    if (attributesObj.text != undefined) {
		        var p = document.createElement("p");
		        $(box).append(p);
		        $(p).html(attributesObj.text);
		    }
		    this.image = {};
		    this.image.object = $(box).get(0);
		    this.image.data = $(box).get(0).innerHTML;
		    this.image.origEle = $(box).get(0);
		    this.image.isFlash = false;
		    this.image.isHtml = true;
		    this.type = "image-popup";
		}
		else if (bits[0].toLowerCase() == "vid") {
		    var box = document.createElement("div");
		    $("body").append(box);
		    $(box).attr("id", bits[1]); 
		    var embed = document.createElement("embed");
		    $(box).append(embed);
		    $(embed).attr("src", "/flvplayer.swf");
		    $(embed).attr("width", "350");
		    $(embed).attr("height", "340");
		    $(embed).attr("allowscriptaccess", "always");
		    $(embed).attr("allowfullscreen", "true");
		    $(embed).attr("showcontrols", "true");
		    $(embed).attr("flashvars", "width=350&height=340&file=" + attributesObj.video + "&frontcolor=0x000000&screencolor=0xFFFFFF&autostart=false");
		    $(embed).bind("load", function() {
		        reposition($(this).attr("rel"));
            });
		    if (attributesObj.text != undefined) {
		        var p = document.createElement("p");
		        $(box).append(p);
		        $(p).html(attributesObj.text);
		    }
		    this.image = {};
		    this.image.object = $(box).get(0);
		    this.image.data = $(box).get(0).innerHTML;
		    this.image.origEle = $(box).get(0);
		    this.image.isFlash = false;
		    this.image.isHtml = true;
		}
	}

	// Optional //
	//////////////

	this.oncloseFunc = function() { };
	this.onopenFunc = function() { };	
	
	this.caption = "";	// Caption

	// If extra attributes have been passed in
	if (typeof(attributesObj) == "object") {
		if (attributesObj.caption != undefined) {	this.caption = attributesObj.caption; }
		if (attributesObj.onclose != undefined) {	this.oncloseFunc = attributesObj.onclose; }
		if (attributesObj.onopen != undefined) {	this.onopenFunc = attributesObj.onopen; }		
	}

	var closedRef = this;
	setTimeout(function() { closedRef.init(); }, 200);
}

RyMacBox.prototype.init = function() {
    var closedRef = this;

    var mbMainContainer = document.createElement("div");
    mbMainContainer.id = this.name;
    mbMainContainer.className = "macbox" + ((this.style.length != 0) ? " macbox" + this.style : "");
    if (this.type != undefined) {
        mbMainContainer.className += " " + this.type;
    }
    var mbWidthAdd = 90;
    if (this.style == "-round") {
        mbWidthAdd = 80;
    }
    else if (this.style == "-basic") {
        mbWidthAdd = 0;
    }
    mbMainContainer.style.width = this.width + mbWidthAdd + "px";

    var mbTopLeft = document.createElement("div");
    mbTopLeft.className = "macbox-top-left";
    var tlWidthAdd = 45;
    if (this.style == "-round") tlWidthAdd = 35;
    if (this.style == "-basic") tlWidthAdd = 0;
    mbTopLeft.style.width = this.width + tlWidthAdd + "px";

    mbMainContainer.appendChild(mbTopLeft);

    var mbTopRight = document.createElement("div");
    mbTopRight.className = "macbox-top-right";

    var mbCloseLink = document.createElement("a");
    mbCloseLink.className = "macbox-close";
    mbCloseLink.innerHTML = "close";
    mbCloseLink.href = "#";
    var name = this.name;
    mbCloseLink.onclick = function() {
        hideRyMacBox(name);
        return false;
    }

    mbTopRight.appendChild(mbCloseLink);

    mbMainContainer.appendChild(mbTopRight);

    var mbMiddle = document.createElement("div");
    mbMiddle.className = "macbox-middle";
    mbMiddle.style.width = this.width + 90 + "px";

    var mbRight = document.createElement("div");
    mbRight.className = "macbox-right";
    mbRight.style.width = this.width + 45 + "px";

    var mbContent = document.createElement("div");
    mbContent.className = "macbox-content";
    mbContent.style.width = this.width + "px";
    if (this.image.isHtml) {
        // Remove the original node
        this.image.origEle.parentNode.removeChild(this.image.origEle);
        //mbContent.innerHTML = this.image.data;
        mbContent.appendChild(this.image.object);
    }
    else if (this.image.isImage) {
        this.image.origEle.parentNode.removeChild(this.image.origEle);
        mbContent.appendChild(this.image.object);
    }
    else {
        var mbImgContainer = document.createElement("div");
        var mbImg = document.createElement("img");
        mbImg.id = this.name + "_image";

        if (!this.image.isFlash) {
            mbImg.src = this.image.src;
            mbImg.alt = "";
        }
        mbImgContainer.appendChild(mbImg);
        mbContent.appendChild(mbImgContainer);

        var mbCaption = document.createElement("div");
        mbCaption.className = "macbox-caption";
        mbCaption.innerHTML = this.caption;
        mbContent.appendChild(mbCaption);
    }

    mbRight.appendChild(mbContent);

    mbMiddle.appendChild(mbRight);

    mbMainContainer.appendChild(mbMiddle);

    var mbBottomLeft = document.createElement("div");
    mbBottomLeft.className = "macbox-bottom-left";
    var blWidthAdd = 45;
    if (this.style == "-round") blWidthAdd = 35;
    if (this.style == "-basic") blWidthAdd = 0;
    mbBottomLeft.style.width = this.width + blWidthAdd + "px";

    mbMainContainer.appendChild(mbBottomLeft);

    var mbBottomRight = document.createElement("div");
    mbBottomRight.className = "macbox-bottom-right";

    mbMainContainer.appendChild(mbBottomRight);

    $(mbMainContainer).hide();

    var closedRef = this;
    setTimeout(function() { closedRef.output.appendChild(mbMainContainer); }, 0);

    if (this.image.isFlash) {
        swfobject.embedSWF("images/test.swf", this.name + "_image", this.width, this.height, "9.0.0");
    }

    if (this.callbackFunction != null) {
        setTimeout(this.callbackFunction, 200);
    }
}

var macboxObjs = {};
function triggerMacBox(Arguments) {
    //initialise the default attributes
    var defaults = {
        source: "AJAX", // Which source of information we will get. HTML, AJAX, IMAGE
        boxID: "RymacBoxPopup", // Id/name of the pop up
        element: "macbox-popup", //id of element to get html from
        width: 700, // Width of the pop up
        height: 1,  // Height of the pop up, 1 mean auto
        parentObj: $("body").get(0), // html DOM object. The pop up will be insert at the end of this object
        ajaxType: "get",
        ajaxUrl: "", // An Url to the ajax the return result should be array in the objArray format
        ajaxData: "", // data to send to the ajax
        borderType: "", // Type of the border could be: round, basic
        image: "", //the image to get
        imageText: "", //the text to show with the image
        video: "", //the video to get
        callback: function() {}, //function to call after running macbox
        onclose: function() {} //function to call after running macbox
    };
    var args = $.extend(defaults, Arguments);
    
    if ($("#" + args.boxID).get(0) != null) {
        showRyMacBox(args.boxID);
    } else {
        if (args.source == "AJAX") {
            $.ajax({
                type: args.ajaxType,
                url: args.ajaxUrl,
                data: args.ajaxData,
                success: function(data, status) {
                    var popup = document.createElement("div");
                    $(popup).attr("id", args.boxID);
                    $(popup).append(data);
                    $("body").append(popup);
                    macboxObjs["_" + args.boxID] = new RyMacBox(args.boxID, "html|" + args.boxID, 
                    args.width, args.height,
                    args.parentObj, { onclose: args.onclose }, {}, function() {
                        showRyMacBox(args.boxID);
                        args.callback();
                    }, true, args.borderType);
                }
            });
        }
        else if (args.source == "HTML") {
            macboxObjs["_" + args.boxID] = new RyMacBox(
                args.boxID, 
                "html|" + args.element,
                args.width,
                args.height,
                args.parentObj, 
                { onclose: args.onclose }, 
                {}, 
                function() {
                    showRyMacBox(args.boxID);
                },
                true,
                args.borderType
            );
        }
        else if (args.source == "IMAGE") {
            var imgSrc = "";
            var imgText = "";
            macboxObjs["_" + args.boxID] = new RyMacBox(
                args.boxID,
                "img|" + args.element,
                args.width,
                args.height,
                args.parentObj,
                { image: args.image, text: args.imageText, onclose: args.onclose },
                {},
                function() {
                    showRyMacBox(args.boxID);
                },
                true,
                args.borderType
            );
        }
        else if (args.source == "VIDEO") {
            var imgSrc = "";
            var imgText = "";
            macboxObjs["_" + args.boxID] = new RyMacBox(
                args.boxID,
                "vid|" + args.element,
                args.width,
                args.height,
                args.parentObj,
                { video: args.video, text: args.imageText, onclose: args.onclose },
                {},
                function() {
                    showRyMacBox(args.boxID);
                },
                true,
                args.borderType
            );
        }
    }
}
