/* Greybox Redux
 * Required: http://jquery.com/
 * Written by: John Resig
 * Based on code by: 4mir Salihefendic (http://amix.dk)
 * License: LGPL (read more in LGPL.txt)
 */
var GB_DONE = false;
var GB_HEIGHT = 1;
var GB_WIDTH = 1;
var GB_VIDEO = null;
var GB_VIDEO_TYPE = null;
var GB_TYPE = null;
var GB_RE = {
    empty: /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i // elements that don't have children
};
function GB_show(caption, url, type, height, width) {
    GB_TYPE = type;

    GB_HEIGHT = height || 1;
    GB_WIDTH = width || 1;
    if (!GB_DONE) {

        $(document.body).append("<div id='GB_overlay' style='visibility:hidden'></div><div id='GB_window' style='visibility:hidden'> <div id='GB_content' style='visibility:hidden'>" + "<div id='lightBoxClose'><img  src='" + applicationPath + "lightbox/close.gif' alt='Close window'/></div></div></div>");

        $("#GB_overlay").attr("style", "height:" + $(document).height() + "px");
        $("#lightBoxClose").click(GB_hide);
        $("#GB_overlay").click(GB_hide);

        window.onscroll = function() {

            GB_position(1);

        };
        GB_DONE = true;
    }
    $("#GB_frame").remove();

    if (type == "GB_IFRAME") {

        $("#GB_content").append("<iframe id='GB_frame' allowtransparency='true' frameborder='0' border='0' src='" + url + "'></iframe>");
        $("#GB_frame").attr("style", "overflow:hidden; visibility:hidden"); //$("#GB_caption").html(caption);
        $("#GB_overlay").show();
    }
    else if (type == "GB_INLINE") {
        $("#GB_content").append("<div class='inlineContent'></div>");
        $("div.inlineContent").attr("style", "overflow:hidden; visibility:hidden");

        $("div.inlineContent").append($("#" + url.split("#")[1]).clone(true).show());

        var prevElement = $("#" + url.split("#")[1]).prev();

        var elementContent = $("div.inlineContent").children("div").clone(true);
        $("#" + url.split("#")[1]).remove();

        $("#GB_window img").click(function() {

            $(prevElement).after(elementContent);
            $("#" + url.split("#")[1]).hide();

        });
        $("#GB_overlay").click(function() {
            $(prevElement).after(elementContent);
            $("#" + url.split("#")[1]).hide();

        });
        GB_WIDTH = 660;
        $("#GB_overlay").show();
        GB_position(0);
    }

}

function GB_videoShow(caption, url, style, height, width, link) {
	var newUrl;
	if (!link) {
		newUrl = "videoInfo.aspx?path=" + url.split("video=")[1].split("&")[0];
	} else {
		newUrl = url;
	}
    var template = '';
    GB_HEIGHT = 550;
    GB_WIDTH = 768;
    var videoUrl, videoType, videoHeading, videoDescription;
    $.ajax({
    	type: "GET",
    	url: newUrl,
    	dataType: "json",
    	success: function (data) {
    		//var videoInformation = $.secureEvalJSON(data);
    		var videoInformation = data;
    		videoUrl = videoInformation.url;
    		videoType = videoInformation.type;
    		videoHeading = videoInformation.title;
    		videoDescription = videoInformation.description;
    		$.ajax({
    			type: "GET",
    			url: "LightboxVideo.aspx",
    			dataType: "html",
    			success: function (data) {
    				if (!GB_DONE) {
    					var closeSuffix = (style == "main") ? "_main" : "";
    					$(document.body).append("<div id='GB_overlay'></div><div id='GB_window'> <div id='GB_content'>" + "<a id='lightBoxClose'><img id='lightBoxClose' src='" + applicationPath + "lightbox/close" + closeSuffix + ".gif' alt='Close window'/></a></div></div>");
    					$("#GB_overlay").attr("style", "height:" + $(document).height() + "px");
    					document.getElementById("GB_window").style.width = "768px";
    					$("#GB_window img").click(GB_hide);
    					$("#GB_overlay").click(GB_hide);
    					$(window).resize(GB_position);
    					window.resize = function () {
    						GB_position(0);
    					};
    					window.onscroll = function () {

    						GB_position(1);
    					};
    					GB_DONE = true;
    				}
    				$("#GB_content").append(data);
    				$("#GB_content h1").text(videoHeading);
    				$("#GB_content h1").addClass(style);
    				$("#GB_content div.col2").text(videoDescription);
    				$("#GB_window").addClass(style);

    				var youtubePatt = /youtube\.com|youtu\.be/i;
    				if (youtubePatt.test(videoUrl)) {
    					// youtube video
    					document.getElementById("GB_content").style.padding = "30px 30px 30px 40px";
    					if (videoUrl.indexOf("/embed/") < 1) {
    						var watchIdPatt = /.*((youtu.be\/)|(v\/)|(embed\/)|(watch\?))\??v?=?([^\s#\&\?]*).*/i;
    						var watchIdMatches = videoUrl.match(watchIdPatt);
    						if (watchIdMatches.length > 6) {
    							videoUrl = "http://www.youtube.com/embed/" + watchIdMatches[6] + "?autoplay=1";
    						}
    					}
    					$("#GB_content div#videoPlayerContainer").append("<iframe id='videoplayer' width='686' height='416' frameborder='0' src='" + videoUrl + "' style='margin-left: 23px;' allowfullscreen></iframe>");
    				} else {
    					var markup;
    					switch (videoType) {
    						case "video/x-ms-wmv":
    							GB_VIDEO_TYPE = "wmv";
    							markup = wmvFile("videoplayer", videoUrl);
    							break;
    						case "video/x-flv":
    							GB_VIDEO_TYPE = "flv";
    							if (style == "main")
    								embedFlashVideo("videoplayer", escape(videoUrl), style);
    							else
    								markup = flvFile("videoplayer", escape(videoUrl));
    							break;
    						case "application/octet-stream":
    							GB_VIDEO_TYPE = "flv";
    							if (style == "main")
    								embedFlashVideo("videoplayer", escape(videoUrl), style);
    							else
    								markup = flvFile("videoplayer", escape(videoUrl));
    							break;
    					}
    					if (markup) {
    						// replace default size with specified height and width
    						if (height) markup.height = height;
    						if (width) markup.width = width;
    						$("#GB_content div#videoPlayerContainer").append(createHTML(markup));
    					}
    				}
    				GB_VIDEO = document.getElementById('videoplayer');
    				$(" #GB_window").attr("style", "overflow:hidden; visibility:hidden; width:768px;");
    				$("#GB_overlay").show();
    				GB_position(0);
    			}
    		});
    	}
    });
}
function GB_showForm() {
    $("#GB_overlay").show();

    $("#GB_content, #GB_frame,  div.inlineContent").css({
        'visibility': 'visible'
    }).parent("#GB_window").css({
        'visibility': 'visible'
    });

}
function GB_hide() {

    $("div#pageContainer object, div#pageContainer embed, div#pageContainer selects").attr("style", " visibility:visible; display:block; ");
    if (GB_VIDEO != null && GB_VIDEO_TYPE == "wmv" && $.browser.msie) {
        GB_VIDEO.controls.stop();
    }
    window.resize = null;
    window.onscroll = null;

    t = setTimeout(function () {
        GB_Destroy();
    },
    100);
}

function GB_Destroy() {
    $("#videoplayer").hide().remove();
    $("#GB_window,#GB_overlay").remove();
    GB_DONE = false;
}
function GB_position(method) {
    var de = document.documentElement;
    var w = self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
    var h = self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
    var offset = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;

    if (GB_TYPE == 'GB_INLINE') {
        if (viewPortHeight() > $("#GB_content").height()) {
            $("#GB_window").css({
                top: offset + ((h - $("#GB_content").height()) / 2) + "px",
                height: "auto",
                width: GB_WIDTH,
                left: ((w - GB_WIDTH) / 2) + "px"
            })
        } else {
            $("#GB_window").css({
                top: 0 + "px",
                height: "auto",
                width: GB_WIDTH,
                left: ((w - GB_WIDTH) / 2) + "px"
            })
        }
    }
    else {

        if ((viewPortHeight() > GB_HEIGHT ) ) {

            $("#GB_window").css({
                top: offset + ((h - GB_HEIGHT) / 2) + "px",
                height: GB_HEIGHT + "px",
                left: ((w - GB_WIDTH) / 2) + "px"
            })

        }
        else if (viewPortHeight() < GB_HEIGHT && method == 0) {

            
            $("#GB_window").css({
                top: offset + "px",
                height: GB_HEIGHT + "px",
                left: ((w - GB_WIDTH) / 2) + "px"
            })

        }

        else if (viewPortHeight() < GB_HEIGHT && method == 1) {
            $("#GB_window").css({
                height: GB_HEIGHT + "px",
                left: ((w - GB_WIDTH) / 2) + "px"
            })
        }
        else {

            $("#GB_window").css({
                top: offset + "px",
                left: ((w - GB_WIDTH) / 2) + "px"
            })
        }

    }

    GB_showForm();
}
function viewPortHeight() {
    var viewportheight; // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    if (typeof window.innerWidth != 'undefined') {
        viewportheight = window.innerHeight
    } // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
        viewportheight = document.documentElement.clientHeight
    } // older versions of IE
    else {
        viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    return viewportheight;
}
function wmvFile(id, url) {
    var autoplay = 1;
    var markup = {
        tag: 'object',
        id: id,
        autoplay: 0,
        controller: "mini",
        height: "423",
        width: "752",
        children: [{
            tag: 'param',
            name: 'autostart',
            value: autoplay
        }]
    };
    if ($.browser.msie) {
        markup.type = 'video/x-ms-wmv';
        markup.classid = 'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6';
        markup.children[markup.children.length] = {
            tag: 'param',
            name: 'url',
            value: url
        };
        markup.children[markup.children.length] = {
            tag: 'param',
            name: 'scale',
            value: "ToFit"
        };
        markup.children[markup.children.length] = {
            tag: 'param',
            name: 'uimode',
            value: markup.controller
        };
    } else {
        markup.type = 'application/x-ms-wmp';
        markup.data = url;
        markup.children[markup.children.length] = {
            tag: 'param',
            name: 'controller',
            value: markup.controller
        };
        markup.children[markup.children.length] = {
            tag: 'param',
            name: 'src',
            value: url
        };
    }
    return markup;
   }

function flvFile(id, url) {
	var markup = {
		tag: 'object',
		id: id,
		autoplay: 0,
		controller: "none",
		height: "423",
		width: "752",
		children: [{}]
	};

	if ($.browser.msie) {
		markup.type = 'application/x-shockwave-flash';
		markup.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
		markup.type = 'application/x-shockwave-flash';
		markup.data = applicationPath + "swf/player.swf?movie=" + url + "&autoplay=on";
		markup.children[markup.children.length] = {
			tag: 'param',
			name: 'movie',
			value: applicationPath + "swf/player.swf?movie=" + url + "&autoplay=on"
		};
		markup.children[markup.children.length] = {
			tag: 'param',
			name: 'allowFullScreen',
			value: true
		};

	} else {
		markup.type = 'application/x-shockwave-flash';
		markup.data = applicationPath + "swf/player.swf?movie=" + url + "";
		markup.children[markup.children.length] = {
			tag: 'param',
			name: 'flashvars',
			value: applicationPath + "swf/player.swf?movie=" + url + "&autoplay=on"
		};
		markup.children[markup.children.length] = {
			tag: 'param',
			name: 'allowFullScreen',
			value: true
		};
	}
	return markup;

}

function embedFlashVideo(id, url, style) {
	var player = (style == 'main') ? "VideoPlayer.swf" : "player.swf";
	var flashvars = { 'initialVideoUrl': url, 'startUpAutoplay': 'true', 'live': 'false', 'skinAutoHide': 'false'};
	var params = { 'allowFullscreen': 'true', 'wmode': 'transparent' };
   	var attributes = { 'id': id };
   	swfobject.embedSWF(applicationPath + "swf/" + player, "videoPlayerContainer", "752px", "423px", "9.0.124", "false", flashvars, params, attributes);
}

function createHTML(obj) {
    var html = '<' + obj.tag;
    for (var attr in obj) {
        if (attr == 'tag' || attr == 'html' || attr == 'children') continue;
        if (attr == 'cls') {
            html += ' class="' + obj['cls'] + '"';
        } else {
            html += ' ' + attr + '="' + obj[attr] + '"';
        }
    }
    if (GB_RE.empty.test(obj.tag)) {
        html += '/>';
    } else {
        html += '>';
        var cn = obj.children;
        if (cn) {
            for (var i = 0, len = cn.length; i < len; ++i) {
                html += this.createHTML(cn[i]);
            }
        }
        if (obj.html) html += obj.html;
        html += '</' + obj.tag + '>';
    }
    return html;
};
