//Basic Geo - System funcs

//register namespace
function registerNS(ns) {
    var nsParts = ns.split(".");
    var root = window;

    for (var i = 0; i < nsParts.length; i++) {
        if (typeof root[nsParts[i]] == "undefined")
            root[nsParts[i]] = new Object();

        root = root[nsParts[i]];
    }
}

registerNS("GeoSys");

Function.prototype.bind = function(o) {
    if (!window.__objs) {
        window.__objs = [];
        window.__funcs = [];
    }

    var objId = o.__oid;
    if (!objId)
        __objs[objId = o.__oid = __objs.length] = o;

    var me = this;
    var funcId = me.__fid;
    if (!funcId)
        __funcs[funcId = me.__fid = __funcs.length] = me;

    if (!o.__closures)
        o.__closures = [];

    var closure = o.__closures[funcId];
    if (closure)
        return closure;

    o = null;
    me = null;

    return __objs[objId].__closures[funcId] = function() {
        return __funcs[funcId].apply(__objs[objId], arguments);
    };
}


//obj inheritance
//http://duncanpierce.org/node/185
function extend(superType) {
    var intermediateConstructor = function() { };
    intermediateConstructor.prototype = superType.prototype;
    return new intermediateConstructor();
};

GeoSys.ContentLoader = function(serviceUrl, data, event) {

    var dt = {};
    if (data) { dt = data; }
    if (typeof dt != "string") dt = JSON.stringify(dt);

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: serviceUrl,
        data: dt,
        dataType: "json",
        success: function(res) {
            event(res);
        }
    }); //ajax
};






/// <reference path="~/Resources/scripts/jquery-1.3.1-vsdoc.js" />
Type.registerNamespace("Helper");






Helper.parseLocalFloat = function(o) {
    var s = o.toString();

    if (s.indexOf(',', 0) > -1)
        return parseFloat(s.replace(/,/, '.'));
    else
        return parseFloat(s);
}



// ide az abszolut közöset pakoljuk , a keretrendszer loadolja 






function addEvent(o, evType, f, capture) {
    if (o.addEventListener) {
        o.addEventListener(evType, f, capture);
        return true;
    } else if (o.attachEvent) {
        var r = o.attachEvent("on" + evType, f);
        return r;
    } else {
        alert("Handler could not be attached");
    }
}

//Kiszedi hogy a fgv Event paramsából hogy ki volt a hivó object 
function GetCallerObject(e) {
    if (e.srcElement) { return e.srcElement; }
    else if (e.target) { return e.target; }
    else { alert("Invalid Caller Object"); }

}

/**  * extract the substring from full string, between start string and end string  
* @param {Object} full  *
 @param {Object} start  * 
 @param {Object} end  */
function extractString(full, start, end) {
    var i = (start === '') ? 0 : full.indexOf(start);
    var e = end === '' ? full.length : full.indexOf(end, i + start.length);
    return full.substring(i + start.length, e);
  } 

//egy editboxba ir hogy az updatepanel postolódjon
function FireUpdatePanel(hiddened) {


    var hiddenField = $get(hiddened);
    if (hiddenField) {
        var d = new Date()
        hiddenField.value = d.getTime();
        __doPostBack(hiddened, '');
    }
    return true;
}


//egy editboxba ir hogy az updatepanel postolódjon Keyupra van rákötve
function FireUpdatePanelEvent(ev, hiddened) {


    var hiddenField = $get(hiddened);
    if (hiddenField) {
        var d = new Date()
        hiddenField.value = d.getTime();
        __doPostBack(hiddened, '');
    }
    return true;
}





//****************************** OPENWINDOW FUNC ***************************************
var NFW = null;
var windowW = 400 // wide
var windowH = 300 // high
var intervalIdState
var autoclose = true
var beIE = document.all ? true : false
var GENOPTIONS = "fullscreen, width=" + windowW + ",height=" + windowH
var GENOPTIONS2 = "fullscreen, width=400,height=200";



function OpenContent(url, w, h, ismodal) {

    openAWindow(url, "www", w, h, "center", 0, 0, ismodal);

}

//detailed view 
function OpenContent2(url, w, h, ismodal) {

    openAWindow2(url, "www", w, h, "center", 0, 0, ismodal);
}



function openAWindow(pageToLoad, winName, width, height, align, xposition, yposition, ismodal) {
    if (align == "center") {
        xposition = (screen.availWidth - width) / 2;
        yposition = (screen.availHeight - height) / 2;
    }
    else if (align == "right") {
        xposition = screen.availWidth - xposition - height;
    }

    if (ismodal) {
        args = "dialogHeight:" + height + "px;" +
		            "dialogLeft:" + xposition + "px;" +
					"dialogTop:" + yposition + "px;" +
					 "dialogWidth:" + width + "px;" +
					 "center:yes;" +
				     "status:no;" +
					 "resizable:yes"


    }
    else {
        args = "width=" + width + ","
				  + "height=" + height + ","
				  + "location=0,"
				  + "resizable=1,"
				  + "scrollbars=1,"
				  + "status=0,"
				  + "menubar=1,"
				  + "titlebar=1,"
				  + "toolbar=1,"
				  + "hotkeys=0,"
				  + "left=" + xposition + ","     //IE Only
				  + "top=" + yposition;           //IE Only
    }

    var ran_number = Math.round(Math.random() * 10000);
    var pg = pageToLoad;
    if (pg.lastIndexOf("?") == -1) {
        pg = pg + "?_DMY=" + ran_number;
    }
    else {
        pg = pg + "&_DMY=" + ran_number;
    }


    if (ismodal) {

        window.showModalDialog(pg, winName, args);
    }
    else {
        window.open(pg, winName, args);
    }
}




function openAWindow2(pageToLoad, winName, width, height, align, xposition, yposition, ismodal) {
    if (align == "center") {
        xposition = (screen.availWidth - width) / 2;
        yposition = (screen.availHeight - height) / 2;
    }
    else if (align == "right") {
        xposition = screen.availWidth - xposition - height;
    }

    if (ismodal) {
        args = "dialogHeight:" + height + "px;" +
		            "dialogLeft:" + xposition + "px;" +
					"dialogTop:" + yposition + "px;" +
					 "dialogWidth:" + width + "px;" +
					 "center:yes;" +
					 "status:yes;" +
					 "resizable:yes";


    }
    else {
        args = "width=" + width + ","
				  + "height=" + height + ","
				  + "location=0,"
				  + "resizable=1,"
				  + "scrollbars=1,"
				  + "status=1,"
				  + "menubar=1,"
				  + "titlebar=1,"
				  + "toolbar=1,"
				  + "hotkeys=0,"
				  + "left=" + xposition + ","     //IE Only
				  + "top=" + yposition;           //IE Only
    }

    var ran_number = Math.round(Math.random() * 10000);
    var pg = pageToLoad;
    if (pg.lastIndexOf("?") == -1) {
        pg = pg + "?_DMY=" + ran_number;
    }
    else {
        pg = pg + "&_DMY=" + ran_number;
    }


    if (ismodal) {

        window.showModalDialog(pg, winName, args);
    }
    else {
        window.open(pg, winName, args);
    }
}


/// SENDTOBACK BRINGTOFRONT FUNC ********************************************************	

function getDivs() {
    var arr = new Array();
    var all_divs = document.body.getElementsByTagName("DIV");
    var j = 0;

    for (i = 0; i < all_divs.length; i++)
        if (all_divs.item(i).style.position == 'absolute' ||
            all_divs.item(i).style.position == 'fixed' ||
            all_divs.item(i).style.zIndex != ''
        ) {
        arr[j] = all_divs.item(i);
        j++;
    }

    return arr;
}

function bringToFront(id) {
    //alert(id);
    if (!document.getElementById ||
        !document.getElementsByTagName)
        return;

    var obj = document.getElementById(id);
    if (null == obj) return;

    var divs = getDivs();
    var max_index = 0;
    var cur_index;

    // Compute the maximal z-index of
    // other absolute-positioned divs
    for (i = 0; i < divs.length; i++) {
        var item = divs[i];
        if (item == obj ||
            item.style.zIndex == '')
            continue;

        cur_index = parseInt(item.style.zIndex);
        if (max_index < cur_index) {
            max_index = cur_index;
        }
    }
    //direkt + 2 !!!
    obj.style.zIndex = max_index + 1;


}


function sendToBack(id) {
    if (!document.getElementById ||
        !document.getElementsByTagName)
        return;

    var obj = document.getElementById(id);
    if (null == obj) return;


    var divs = getAbsoluteDivs();
    var min_index = 999999;
    var cur_index;

    if (divs.length < 2)
        return;

    // Compute the minimal z-index of
    // other absolute-positioned divs
    for (i = 0; i < divs.length; i++) {
        var item = divs[i];
        if (item == obj)
            continue;

        if (item.style.zIndex == '') {
            min_index = 0;
            break;
        }

        cur_index = parseInt(item.style.zIndex);
        if (min_index > cur_index) {
            min_index = cur_index;
        }

    }

    if (min_index > parseInt(obj.style.zIndex)) {
        return;
    }

    obj.style.zIndex = 1;

    if (min_index > 1)
        return;

    var add = min_index == 0 ? 2 : 1;

    for (i = 0; i < divs.length; i++) {
        var item = divs[i];
        if (item == obj)
            continue;

        item.style.zIndex += add;
    }
}


//COLLAPSE PANEL **************************************************



function CollapsePanel(behavID) {
    //megvárjuk amig betöltödik
    window.setTimeout(RealCollapsePanel, 500);
}


function RealCollapsePanel() {
    //alert(behavID);

    //var o = $find(behavID);
    var o = $find('PANELEXTENDER');

    //alert(o);
    o._doClose(true);

}


//HIDE OBJECT ******************************************************

function HideObject(id) {

    var o = $get(id);
    if (null != o) {
        o.style.visibility = "hidden";
        o.style.display = "none";
        o.style.height = "0px";
    }
}

function ShowObject(id) {
    //alert(_height);
    var o = $get(id);
    if (null != o) {
        o.style.visibility = "visible";
        o.style.display = "";
        o.style.height = "";
    }
}


//positions


function getTableHeight(firstcell, lastcell) {
    contentTopDiv = document.getElementById(firstcell)
    contentBotDiv = document.getElementById(lastcell)
    contentTop = getPixelsFromTop(contentTopDiv);
    contentBottom = getPixelsFromTop(contentBotDiv);
    contentHeight = contentBottom - contentTop;
    return contentHeight;
}


function getPixelsFromTop(obj) {
    objFromTop = obj.offsetTop;
    while (obj.offsetParent != null) {
        objParent = obj.offsetParent;
        objFromTop += objParent.offsetTop;
        obj = objParent;
    }
    return objFromTop;
}


//misc

function NullV(arg) {
    if (null == arg || arg == "null") return "";
    else return arg;
}

//modalpanel button szürkítés


 Helper.App_Init = function(){
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(Helper.BeginRequest);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Helper.EndRequest);
}


var _tmplCache = {}
this.parseTemplate = function(str, data) {
    /// <summary>
    /// Client side template parser that uses &lt;#= #&gt; and &lt;# code #&gt; expressions.
    /// and # # code blocks for template expansion.
    /// NOTE: chokes on single quotes in the document in some situations
    ///       use &amp;rsquo; for literals in text and avoid any single quote
    ///       attribute delimiters.
    /// </summary>    
    /// <param name="str" type="string">The text of the template to expand</param>    
    /// <param name="data" type="var">
    /// Any data that is to be merged. Pass an object and
    /// that object's properties are visible as variables.
    /// </param>    
    /// <returns type="string" />  
    var err = "";
    try {
        var func = _tmplCache[str];
        if (!func) {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +

            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";


            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err + " # >";
}



//letiltjuk a butonokat
Helper.BeginRequest = function(sender, args) {
    // Find the ID of the UpdatePanel raising the partial postback.
    var sendingPanelID = sender._postBackSettings.panelID.split("|")[0];

    // Using that ID, get a reference to that UpdatePanel's div.
    //var sendingPanel = document.getElementById(sendingPanelID);
    sendingPanelID = sendingPanelID.replace(/\$/gi, '_');
    var sendingPanel = $get(sendingPanelID);

    if (null == sendingPanel) return;

    // Get an array of all the input elements in that div.
    var inputs = sendingPanel.getElementsByTagName('input');

    // Loop through the elements and check each one's type.
    //  if it's a submit type element, disable it.
    for (element in inputs) {
        try {
            if (null != inputs[element].type && (inputs[element].type == 'submit' || inputs[element].type == 'image')) {
                inputs[element].disabled = true;
                inputs[element].blur();
            }
        }
        catch (Error) {
        }
    }

    $("#" + sendingPanelID + " a[class^=btn]").fadeTo("slow", 0.11).attr("disabled", "disabled");


}

//visszaállítjuk
Helper.EndRequest = function(sender, args) {


    if (args.get_error() != undefined) {
        // If there is, show the custom error.
        var err = args.get_error().message;
        var err0 = args.get_error().message;
        // $get('Error').style.visibility = "visible";

        // Let the framework know that the error is handled,
        //  so it doesn't throw the JavaScript alert.

        if (args.get_error().httpStatusCode == 500) {
            //try {
            var s = args.get_response().get_responseData();
            err = extractString(s, "<title>", "</title>");
            if (err != null && err != 'undefined' && err != "")
            { }
            else err = err0;
        }
        args.set_errorHandled(true);
        TrackHelpers.GrowlError(err);
    }



    // Find the ID of the UpdatePanel raising the partial postback.
    var sendingPanelID = sender._postBackSettings.panelID.split("|")[0];

    // Using that ID, get a reference to that UpdatePanel's div.
    //var sendingPanel = document.getElementById(sendingPanelID);
    sendingPanelID = sendingPanelID.replace(/\$/gi, '_');
    var sendingPanel = $get(sendingPanelID);

    if (null == sendingPanel) return;

    // Get an array of all the input elements in that div.
    var inputs = sendingPanel.getElementsByTagName('input');

    // Loop through the elements and check each one's type.
    //  if it's a submit type element, disable it.  
    for (element in inputs) {
        try {
            if (null != inputs[element].type && (inputs[element].type == 'submit' || inputs[element].type == 'image'))
                inputs[element].disabled = false;
        }
        catch (Error) {
        }
    }
}

Helper.numb = function(num) {
    return parseInt(num) || 0;
}


Helper.isDefined = function(variable) {
    return eval('(typeof(' + variable + ') != "undefined");');
}


Helper.ContentLoader2 = function(serviceUrl, data, event) {

    var dt = {};
    if (data) { dt = data; }
    if (typeof dt != "string") dt = JSON.stringify(dt);

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: serviceUrl,
        data: dt,
        dataType: "json",
        success: function(res) {
            event(res);
        }
    }); //ajax
};





JQID = function(_baseID, _ctrID) {
    return "#" + _baseID + "_" + _ctrID;
}


JQID2 = function(elemName, ctrID) {
    return elemName + "[id$=" + ctrID + "]";
}


$.fn.waitOn = function(pos, options) {

    var opt = { dx: 0,
        dy: 0
    };
    $.extend(opt, options);
    return this.each(function(i) {
        var el = $(this);
        var x0 = el.offset().left + opt.dx; //igy teljesen ok
        var y0 = el.offset().top + opt.dy;
        var d = 8;

        var w = el.outerWidth();
        if ($.browser.msie) w += Helper.numb($(this).css('padding-left')) + Helper.numb($(this).css('padding-right'));

        //- parseInt(el.css("margin-right"));
        if (pos == "left") { x0 = x0 - 16; y0 = y0 + el.outerHeight() / 2 - 8; }
        else if (pos == "right") { x0 = x0 + w; y0 = y0 + el.outerHeight() / 2 - 8; }
        else if (pos == "center") { x0 = x0 + w / 2 - 8; y0 = y0 + el.outerHeight() / 2 - 8; }
        var target = $("<div id='_dv_progress_' class='miniprogress' style='left:" + x0 + "px;top:" + y0 + "px'></div>");
        target.appendTo($("body"));



    });
}


jQuery.waitOff = function() {

$("#_dv_progress_").remove();
}




//*** curvy corner wrapper */

$.fn.corner = function(options) {


    var settings = {
        tl: { radius: 10 },
        tr: { radius: 10 },
        bl: { radius: 10 },
        br: { radius: 10 },
        antiAlias: true,
        autoPad: true,
        validTags: ["div"]
    };
    if (options && typeof (options) != 'string')
        jQuery.extend(settings, options);


    return this.each(function() {
        new curvyObject(settings, this).applyCorners();
        //new curvyCorners(settings, this ).applyCornersToAll(); 
    });

};

///Getscript WITH cahce option
$.getScript = function(url, cache, callback) {
    $.ajax({
        type: "GET",
        url: url,
        success: callback,
        dataType: "script",
        cache: cache
    });
};







/// <reference name="MicrosoftAjax.js"/>
Sys.Application.add_init(Helper.App_Init);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();/// <reference path="~/Resources/scripts/jquery-1.3.1-vsdoc.js" />
//misc TrackHelper Func

Type.registerNamespace("TrackHelpers");


var HINTSTYLE = { fill: '#ffffe1', cssStyles: { color: '#333333', fontWeight: 'normal', fontSize: '11px' }, hoverIntentOpts: { interval: 350, timeout: 1} };


TrackHelpers.ShowEmailControl = function(trId, baseId)
{
	TrackControl.GetEmailControl(trId, baseId, TrackHelpers.ClbFunc1);
}

TrackHelpers.ShowShareControl = function(trRestId, baseId)
{
	TrackControl.GetShareControl(trRestId, baseId, TrackHelpers.ClbFunc1);
}


TrackHelpers.ClbFunc1 = function(paramObject)
{

	var pnl = $get(paramObject.BaseId + "_dvPanelContent");
	pnl.innerHTML = paramObject.ControlContent;

}




TrackHelpers.showCalendar = function(sender, args)
{
	//$('#' + sender._popupDiv.id).bgiframe(); //IE6nál eltakarja a combót
	//$('#' + sender._popupDiv.id).top
	bringToFront(sender._popupDiv.id);
}



TrackHelpers.SendTrackMail = function(trId, baseId)
{

	$get(baseId + "_imgWait").style.visibility = "visible";
	$get(baseId + "_lbErr").innerHTML = "";

	TrackControl.SendEmail(baseId, trId, $get(baseId + "_edAdr").value,
    $get(baseId + "_edComment").value,
    TrackHelpers.ClbFunc2);

}

//media panel
TrackHelpers.ShowTrMediaTh = function()
{

	$("div.trl_mediapanel").each(
    function(i, v)
    {
    	var pnl = $(v);
    	$.ajax({
    		type: "POST",
    		contentType: "application/json; charset=utf-8",
    		url: TrackHelpers.rootUrl + "Services/TrackServices.asmx/RenderTrackMediaList",
    		data: '{trID:' + pnl.attr("TrID") + '}',
    		dataType: "json",
    		success: function(res)
    		{
    			pnl.html(res.d.ControlContent);

    			if ($("#" + res.d.BaseId + "_btnLeft4").size() > 0)
    			{
    				$("#" + res.d.BaseId + "_wpScroll4").scrollable({
    					size: 5,
    					next: "#" + res.d.BaseId + "_btnRight4",
    					prev: "#" + res.d.BaseId + "_btnLeft4"
    				});
    			}

    			$("#" + res.d.BaseId + "_wpScroll4 a").flyout(
                {

                	//loadingSrc: TrackHelpers.rootUrl + 'resources/images/pics/busy.gif',
                	loadingText: 'Betöltés...',
                	closeTip: 'A bezáráshoz kattints a képre'
                	// loader: 'thloader2',
                	//loaderZIndex: 10001
                }
				);



    		}
    	});
    }
);

}

TrackHelpers.ClbFunc2 = function(paramObject)
{

	$get(paramObject.BaseId + "_imgWait").style.visibility = "hidden";
	if (paramObject.ErrStr != "")
	{
		$get(paramObject.BaseId + "_lbErr").innerHTML = paramObject.ErrStr;
	}
	else
	{
		$get(paramObject.BaseId + "_lbErr").innerHTML = "OK";
		$get(paramObject.BaseId + "_btnSendMail").disabled = true;

	}
}

TrackHelpers.GetScriptPackage = function(pkgName, clbFunc)
{
	$.getScript(TrackHelpers.rootUrl + "Main/ScriptMaster.ashx?v=" + TrackHelpers.cacheVersion + "&ScrSet=" + pkgName, true, clbFunc);
}

TrackHelpers.StartInfos = function()
{
	$(".info_gen").bt(HINTSTYLE);
}

TrackHelpers.BlockUI = function() {
    $("div[id$=UpdateProgress2]").show();
}

TrackHelpers.UnBlockUI = function() {
    $("div[id$=UpdateProgress2]").hide();
}


TrackHelpers.GetTemplate = function(path, event) {
    $.getJSON(TrackConfig.RootUrl + "Services/CommonServices.ashx?ver=" + TrackConfig.CacheVersion,
                    { tpl: path },
                    function(res) {
                        //if (KSZF.HandleGenError(res)) return;
                        event(res);
                    }
                    );
}                   



TrackHelpers.StartDefaultPage = function()
{


	//$ = jQuery.noConflict();


	$.ajax({
	    type: "POST",
	    contentType: "application/json; charset=utf-8",
	    url: TrackHelpers.rootUrl + "Services/TrackServices.asmx/RenderTrackBox",
	    data: "{tp:'YT'}",
	    dataType: "json",
	    success: function(res) {
	    $("#plhYT").html(res.d.ControlContent);
	    }
	});


	

	window.setTimeout(function()
	{
		TrackHelpers.GetScriptPackage("SCRIPTSET_JQUI");
		TrackHelpers.GetScriptPackage("SCRIPTSET_TINY_MCE");
	}, 5000);

 
  
 

}

//***** TinyMCe

var _MCEConfigArray = [{

	mode: 'exact',
	theme: 'advanced',
	plugins: 'emotions',
	theme_advanced_buttons1: 'bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,outdent,indent,separator,cut,copy,paste,undo,redo,separator,link,unlink,image,emotions,fontsizeselect',
	theme_advanced_buttons2: '',
	theme_advanced_buttons3: ''
},
{
	mode: 'exact',
	theme: 'advanced',
	plugins: 'emotions',
	theme_advanced_buttons1: 'bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,paste,separator,link,unlink,image,emotions',
	theme_advanced_buttons2: '',
	theme_advanced_buttons3: ''
}
]

//
//TrackHelpers.onTinyMCELoad = function() {
//  
//    
//}

TrackHelpers.StartTinyMCE = function()
{
	//TrackHelpers.GetScriptPackage("SCRIPTSET_TINY_MCE", TrackHelpers.onTinyMCELoad);
	tinyMCE.init({
		mode: 'exact',
		theme: 'advanced',
		plugins: 'emotions',
		theme_advanced_buttons1: 'bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,outdent,indent,separator,cut,copy,paste,undo,redo,separator,link,unlink,image,emotions,fontsizeselect',
		theme_advanced_buttons2: '',
		theme_advanced_buttons3: ''
	});
}


TrackHelpers.GetTrackCloudAsync = function()
{
	$.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: TrackHelpers.rootUrl + "Services/TrackServices.asmx/RenderTrackCloud",
		data: '{}',
		dataType: "json",
		success: function(res)
		{
			$("#trCloudBdy").html(res.d.ControlContent);
		}
	});
}


TrackHelpers.GrowlError = function(errTxt)
{
	if (jQuery().effect) { TrackHelpers._GrowlError(errTxt) }
	else TrackHelpers.GetScriptPackage("SCRIPTSET_JQUI", TrackHelpers._GrowlError(errTxt));
}

TrackHelpers._GrowlError = function(errTxt)
{
	$.toaster({ text: errTxt });
}

//for jquery $.Ajax call
TrackHelpers.TrackAjaxError = function(info, xhr)
{
    try
    {
        var err = eval("(" + xhr.responseText + ")");
        TrackHelpers.GrowlError(err.Message)
    }
    catch (e)
    {
        try
        {
            TrackHelpers.GrowlError(xhr.responseText);
        } catch (e)
        {
 
        }
    }
}

// Callback function invoked when a call to a  service methods fails.
TrackHelpers.ProxyAjaxError = function(error, userContext, methodName)
{
	if (error !== null)
	{
		TrackHelpers.GrowlError("Hiba történt :" + methodName + "-" + error.get_message());
	}
}



//Master hivja minden esetben !!!!
TrackHelpers.AutoExecBat = function()
{
	$("<div></div>").ajaxError(TrackHelpers.TrackAjaxError);
}


TrackHelpers.Confirm = function(message, callback, title)
{	
	if ((title == null) || (!title))
		title = "Művelet megerősítése";

	if ((callback != null) || (typeof(callback) == "function"))
		jConfirm(message, title, callback);
	else
		jConfirm(message, title);
}


TrackHelpers.Alert = function(message, postFunc) {
    if (postFunc) {
        jAlert(message, "Üzenet",postFunc);
    }
    else jAlert(message, "Üzenet");
}

TrackHelpers.DisableBtn = function(btnID) {
    var btn = $("#" + btnID);

    if (btn.data('events') && btn.data('events').click) {

        btn.data('clk', btn.data('events').click);
        btn.data('events').click = null;  //lenullázzuk ez event tárhelyét
    }
    
    //btn.unbind("click");
    btn.fadeTo("slow", 0.11).attr("disabled", "disabled");


}

TrackHelpers.EnableBtn = function(btnID) {
    var btn = $("#" + btnID);
    btn.removeAttr("disabled").fadeTo("slow", 1);
    if (btn.data('clk')) {
        btn.data('events').click = btn.data('clk'); //visszatesszük
    }
}


TrackHelpers.HandleError = function(jsonRes) {

    if (typeof jsonRes.d != 'undefined' && "" != jsonRes.d.ErrStr) {
        $.waitOff();
        alert(jsonRes.d.ErrStr, "Hiba történt az alkalmazásban");
        return true;
    }
    else if (typeof jsonRes.ErrStr != 'undefined' && "" != jsonRes.ErrStr) {
        $.waitOff();
        alert(jsonRes.ErrStr, "Hiba történt az alkalmazásban");
        return true;
    }
    return false;
}






if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
// 
// History:
//
//		1.00 - Released (29 December 2008)
//
//		1.01 - Fixed bug where unbinding would destroy all resize events
//
// License:
// 
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC. 
//
(function($) {
	
	$.alerts = {
		
		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
		
		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: '&nbsp;OK&nbsp;',         // text for the OK button
		cancelButton: '&nbsp;M&eacute;gse&nbsp;', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div id="popup_container">' +
			    '<h1 id="popup_title"></h1>' +
			    '<div id="popup_content">' +
			      '<div id="popup_message"></div>' +
				'</div>' +
			  '</div>');
			
			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			
			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});
			
			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
			
			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
		
	}
	
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
})(jQuery);/*
 * JQToaster
 *
 * Copyright (c) 2008 Martin Holzhauer (martin.holzhauer.eu)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: $
 * $Rev: $
 */

jQuery.toasterSetting = {
        timeout: 3000,			// timeout to close the toast
        title: '',				// title of the toast
        text: '',				// text of the toast
        animationSpeed: 500,	// animationSpeed to popup a toast
		_position:'br',			// br, bl, tr, tl
		cssclass:'',			// additional class for the toast
		onlyone:false,			// only one of this toast can appear at the same time
		base:'body',			// base of the toaster area
		closable:false,			// is the toast cloasable
		onclose:false,			// callback function when the toast cloases: callback(cssIdOfTheToast)
		oncreate:false,			// callback that is called after creation of the toast: callback(cssIdOfTheToast)
        hideAlgo:'perPosition'  // hide algorythm of toasts perPosition, global or none
    };

if(!Array.myIndexOf)
{
    Array.prototype.myIndexOf = function(el)
    {
        for(var i = 0; i < this.length; i++) if(el == this[i]) return i;
    }
}

/**
 * @author holzhauer
 */
jQuery.toaster = function(settings) {
    settings = jQuery.extend(jQuery.toasterSetting, settings);

    if (settings.timeout == 0) {
        settings.closable = true;
    }

    var msgId = 'toast' + Math.floor(Math.random() * 1000000);

    var actualMsgCounter = null;
    if (settings.hideAlgo == 'global') {
        this.toasterMsgCounter = this.toasterMsgCounter || new Array();
        this.toasterMsgCounter.push(msgId);
        actualMsgCounter = this.toasterMsgCounter;
    }
    else if (settings.hideAlgo == 'perPosition') {
        this.toasterMsgCounter = this.toasterMsgCounter || new Array();
        this.toasterMsgCounter[settings.base] = this.toasterMsgCounter[settings.base] || new Array();
        this.toasterMsgCounter[settings.base][settings._position] = this.toasterMsgCounter[settings.base][settings.position] || new Array();
        this.toasterMsgCounter[settings.base][settings._position].push(msgId);

        actualMsgCounter = this.toasterMsgCounter[settings.base][settings._position];
    }



    if (jQuery(settings.base + ' > .ui-toaster-area-' + settings._position).length == 0) {
        var toasterArea = '<div class="ui-toaster-area-' + settings._position + '"></div>';
        jQuery(settings.base).append(toasterArea);
    }

    if (settings.onlyone == false || (settings.onlyone == true && $(settings.base + ' > div.ui-toaster-area-' + settings._position + ' div.ui-toaster').length == 0)) {
        var html = '<div class="ui-toaster ' + settings.cssclass + '" id="' + msgId + '">';

        if (settings.closable == true) {
            html += '<span title="Close" class="ui-toaster-close">X</span>';
        }

        if (!!settings.title) {
            html += '<h4 class="ui-toaster-title">' + settings.title + '</h4>';
        }

        html += '<p class="ui-toaster-content">' + settings.text + '</p>';
        html = jQuery(html);

        if (settings._position == 'bl' || settings._position == 'br') {
            jQuery(settings.base + ' > .ui-toaster-area-' + settings._position).prepend(html);
        }
        else if (settings._position == 'tl' || settings._position == 'tr') {
            jQuery(settings.base + ' > .ui-toaster-area-' + settings._position).append(html);
        }

        html.slideDown(settings.animationSpeed);

        // call onCreate callback
        if (typeof settings.oncreate == 'function') {
            settings.oncreate(msgId);
        }

        // create the close function
        var closeFunction = function() {
            jQuery('#' + msgId).slideUp(settings.animationSpeed, function() { jQuery('#' + msgId).remove(); });
            if (typeof settings.onclose == 'function') {
                settings.onclose(msgId);
            }
        }

        // add close function to the "X"
        if (settings.closable == true) {
            jQuery('#' + msgId + ' span.ui-toaster-close').click(function() {
                closeFunction();
            });
        }

        // add the timeout to the toast
        if (settings.timeout > 0) {
            var beforeId = settings.hideAlgo == 'none' ? null : actualMsgCounter.myIndexOf(msgId);
            var before = settings.hideAlgo == 'none' ? null : actualMsgCounter[(beforeId - 1)];

            var timedCloseFunction = function() {
                if (settings.hideAlgo == 'none' || before == undefined || $('#' + before).length == 0) {
                    closeFunction();
                }
                else {
                    window.setTimeout(timedCloseFunction, settings.timeout);
                }
            }

            window.setTimeout(timedCloseFunction, settings.timeout);
        }
    }
};
/// <reference path="~/Resources/scripts/jquery-1.3.1-vsdoc.js" />

Type.registerNamespace("MyGTracks");
//registerNS("MyGTracks")

MyGTracks.FaceBook = function(_appID) {
    this.AppID = _appID;
    this.CallFunc = null;
    this.CallData = null;
    this.IsInit = false;
    this.IsEnsureInit = false;
    this.trData = null;
    this.waitForFB();

}


MyGTracks.FaceBook.prototype.FBStarted = function() {
    var thisobj = this;
    if (this.IsInit) return;
    this.IsInit = true;
    FB.init(this.AppID);

    FB.ensureInit(function() {
    thisobj.IsEnsureInit = true;
    
        $("#btnFBLogout").unbind("click").click(function() {
            FB.Connect.logout(thisobj.onLogOut.bind(thisobj));
        });

        //FB.Connect.ifUserConnected(TrackHelpers.onLoggedIn, TrackHelpers.onLoggedOut);
    });



}


MyGTracks.FaceBook.prototype.onLoggedIn = function() {
    window.location.href = TrackConfig.RootUrl + "Default.aspx";
}




MyGTracks.FaceBook.prototype.onLogOut = function() {
    window.location.href = TrackConfig.RootUrl + "Default.aspx";
    //window.location.reload(true);
}


MyGTracks.FaceBook.prototype.waitForFB = function() {

    if (!Helper.isDefined("FB")) {
        setTimeout(this.waitForFB.bind(this), 1);
        return;
    }
    else {
        this.FBStarted();
    }
}


MyGTracks.FaceBook.prototype.SafeExecute = function() {

    if (!Helper.isDefined("FB") || !this.IsInit || !this.IsEnsureInit) {
        setTimeout(this.SafeExecute.bind(this), 1);
        return;
    }
    else {
        if (this.CallFunc) {
            this.CallFunc(this.CallData);
        }
    }

}


MyGTracks.FaceBook.prototype.PublishTrack = function() {


    this.CallFunc = this._PublishTrack.bind(this);
    this.SafeExecute();
}

MyGTracks.FaceBook.prototype._PublishTrack = function(par) {
    
    if (!$("input[id$=chkFBSaveTrack]").is(":checked")) {
        return;
    }


    



    var attachment = {
    
        'name':  $("input[id$=_tbTrackName]").val(),// this.trData.Title,
        'href': this.trData.TrackUrl,
        'caption': this.trData.Caption,
        'description': this.trData.Description,
        'media': [
       { 'type': 'image',
           'src': this.trData.TrackImageUrl,
           'href': this.trData.TrackUrl
       }
        ]
    };

    //  'name': 'i\'m bursting with joy', 'href': ' http://bit.ly/187gO1', 'caption': '{*actor*} rated the lolcat 5 stars', 'description': 'a funny looking cat', 'properties': { 'category': { 'text': 'humor', 'href': 'http://bit.ly/KYbaN'}, 'ratings': '5 stars' }, 

    var action_links = [{ "text": "Megtekintés", "href": this.trData.TrackUrl}];


    var clb = function(id, ex) {
        // alert(ex);
    }


    FB.Connect.streamPublish(
    "", //par.Title,
    attachment,
    action_links);
    //,//action_links,
    //null, //String  target_id,  
    //null, //String  user_message_prompt,  
    //clb, //Function  callback,  
    //false, //Boolean  auto_publish,  
    //null //String  actor_id
    //);

    $("input[id$=chkFBSaveTrack]").attr("checked", false);

}


MyGTracks.FaceBook.prototype.FBInitSaveTrack = function(_par) {
    if (this.trData != null) return;
    this.trData = _par;
    var thisobj = this;
    $("a[id$=_BtnSave]").click(
    function() {
        thisobj.PublishTrack();
    });
}



//wait for FB
FBTrackInit = function(par) {

    var wait = function() {
        if (FBApp == null) {
            setTimeout(wait, 1);
        }
        else {
            FBApp.FBInitSaveTrack(par);
        }
    }

    wait();

}


var FBApp = null;
MyGTracks.StartFB = function(appID) {
    FBApp = new MyGTracks.FaceBook(appID);
};

/*
 * tools.expose 1.0.5 - Make HTML elements stand out
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/expose.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : June 2008
 * Date: ${date}
 * Revision: ${revision} 
 */
(function(b){b.tools=b.tools||{};b.tools.expose={version:"1.0.5",conf:{maskId:null,loadSpeed:"slow",closeSpeed:"fast",closeOnClick:true,closeOnEsc:true,zIndex:9998,opacity:0.8,color:"#456",api:false}};function a(){if(b.browser.msie){var f=b(document).height(),e=b(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,f-e<20?e:f]}return[b(window).width(),b(document).height()]}function c(h,g){var e=this,j=b(this),d=null,f=false,i=0;b.each(g,function(k,l){if(b.isFunction(l)){j.bind(k,l)}});b(window).resize(function(){e.fit()});b.extend(this,{getMask:function(){return d},getExposed:function(){return h},getConf:function(){return g},isLoaded:function(){return f},load:function(n){if(f){return e}i=h.eq(0).css("zIndex");if(g.maskId){d=b("#"+g.maskId)}if(!d||!d.length){var l=a();d=b("<div/>").css({position:"absolute",top:0,left:0,width:l[0],height:l[1],display:"none",opacity:0,zIndex:g.zIndex});if(g.maskId){d.attr("id",g.maskId)}b("body").append(d);var k=d.css("backgroundColor");if(!k||k=="transparent"||k=="rgba(0, 0, 0, 0)"){d.css("backgroundColor",g.color)}if(g.closeOnEsc){b(document).bind("keydown.unexpose",function(o){if(o.keyCode==27){e.close()}})}if(g.closeOnClick){d.bind("click.unexpose",function(o){e.close(o)})}}n=n||b.Event();n.type="onBeforeLoad";j.trigger(n);if(n.isDefaultPrevented()){return e}b.each(h,function(){var o=b(this);if(!/relative|absolute|fixed/i.test(o.css("position"))){o.css("position","relative")}});h.css({zIndex:Math.max(g.zIndex+1,i=="auto"?0:i)});var m=d.height();if(!this.isLoaded()){d.css({opacity:0,display:"block"}).fadeTo(g.loadSpeed,g.opacity,function(){if(d.height()!=m){d.css("height",m)}n.type="onLoad";j.trigger(n)})}f=true;return e},close:function(k){if(!f){return e}k=k||b.Event();k.type="onBeforeClose";j.trigger(k);if(k.isDefaultPrevented()){return e}d.fadeOut(g.closeSpeed,function(){k.type="onClose";j.trigger(k);h.css({zIndex:b.browser.msie?i:null})});f=false;return e},fit:function(){if(d){var k=a();d.css({width:k[0],height:k[1]})}},bind:function(k,l){j.bind(k,l);return e},unbind:function(k){j.unbind(k);return e}});b.each("onBeforeLoad,onLoad,onBeforeClose,onClose".split(","),function(k,l){e[l]=function(m){return e.bind(l,m)}})}b.fn.expose=function(d){var e=this.eq(typeof d=="number"?d:0).data("expose");if(e){return e}if(typeof d=="string"){d={color:d}}var f=b.extend({},b.tools.expose.conf);d=b.extend(f,d);this.each(function(){e=new c(b(this),d);b(this).data("expose",e)});return d.api?e:this}})(jQuery);/////
// Open
//
// Popup window utility for creating pop up windows without intrusive using any
// intrusive code.
//
// 
///

///
//     
//     <a href="http://example.com" target="_blank" class="myPopup">Open popup window.</a>

//    <script type="text/javascript>
//       $("a.myPopup").open({
//          width: 400,
//          height: 300,
//          scrollbars: false
//       });
//    </script>

///

(function($) {

    $.open = {};

    // Default popup window parameters
    $.open.defaultParams = {
        "width": "800",   // Window width
        "height": "600",   // Window height
        "top": "0",     // Y offset (in pixels) from top of screen
        "left": "0",     // X offset (in pixels) from left side of screen
        "directories": "no",    // Show directories/Links bar?
        "location": "no",    // Show location/address bar?
        "resizeable": "yes",   // Make the window resizable?
        "menubar": "no",    // Show the menu bar?
        "toolbar": "no",    // Show the tool (Back button etc.) bar?
        "scrollbars": "yes",   // Show scrollbars?
        "status": "no"     // Show the status bar?
    };


    // Some configuration properties
    $.open.defaultConfig = {
        autoFocus: true
    };


    // Open popup window static function
    $.open.newWindow = function(href, params, config) {

        // Popup window defaults (don't leave it to the browser)
        var windowParams = $.extend($.open.defaultParams, params);

        // Configuration properties
        var windowConfig = $.extend($.open.defaultConfig, config);

        var windowName = params["windowName"] || "new_window";

        if (parseInt(windowParams.left) == -1) { //konvenció
            var winH = $(window).height();
            var winW = $(window).width();
            windowParams.top= winH / 2 - (parseInt(windowParams.height) / 2);
            windowParams.left= winW / 2 - (parseInt(windowParams.width) / 2);
            
        }


        var i, paramString = "";

        for (i in windowParams) {
            if (windowParams.hasOwnProperty(i)) {
                paramString += (paramString === "") ? "" : ",";
                paramString += i + "=";

                // Allow true/false instead of yes/no in params
                if (windowParams[i] === true || windowParams[i] === false) {
                    paramString += (windowParams[i]) ? "yes" : "no";
                }
                else {
                    paramString += windowParams[i];
                }
            }
        }
        //alert(paramString);
        var popupWindow = window.open(href, windowName, paramString);

        if (windowConfig.autoFocus) {
            popupWindow.focus();
        }

        return popupWindow;
    };


    // Plugin method: $("...").popup()
    $.fn.open = function(parameters, callback) {

        var params = parameters.params || parameters;
        var config = parameters.config || {};

        // Loop over all matching elements
        this.each(function() {

            // Add an onClick behavior to this element
            $(this).click(function(event) {

                // Prevent the browser's default onClick handler
                event.preventDefault();

                // Use the target attribute as the window name
                if ($(this).attr("target")) {
                    params.windowName = $(this).attr("target");
                }

                // Determine the url to open
                //   Use param.href over element's href
                var href;
                if (params.href) {
                    href = params.href;
                }
                else if ($(this).attr("href")) {
                    href = $(this).attr("href");
                }
                else {
                    return;  // Can't openWindow anything, so stop here
                }


                // Pop up the window
                var windowObject = $.open.newWindow(href, params, config);

                if (callback) {
                    callback(windowObject);
                }
            });
        });

        return $;
    };

})(jQuery);