$().ready(function() {
    // animation
    jQuery.fn.fadeToggle = function(speed, easing, callback) {
        return this.animate({ opacity: 'toggle' }, speed, easing, callback);
    };

    // ajax
    $.ajaxSetup(
	{
	    dataType: "json"
	});

    (function($) {
        m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
    $.toJSON = function(value, whitelist) {
        var a,          // The array holding the partial texts.
            i,          // The loop counter.
            k,          // The member key.
            l,          // Length.
            r = /["\\\x00-\x1f\x7f-\x9f]/g,
            v;          // The member value.

        switch (typeof value) {
            case 'string':
                return r.test(value) ? '"' + value.replace(r, function(a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
                }) + '"' :
                '"' + value + '"';

            case 'number':
                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':
                return String(value);

            case 'object':
                if (!value) {
                    return 'null';
                }
                if (typeof value.toJSON === 'function') {
                    return $.toJSON(value.toJSON());
                }
                a = [];
                if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length'))) {
                    l = value.length;
                    for (i = 0; i < l; i += 1) {
                        a.push($.toJSON(value[i], whitelist) || 'null');
                    }
                    return '[' + a.join(',') + ']';
                }
                if (whitelist) {
                    l = whitelist.length;
                    for (i = 0; i < l; i += 1) {
                        k = whitelist[i];
                        if (typeof k === 'string') {
                            v = $.toJSON(value[k], whitelist);
                            if (v) {
                                a.push($.toJSON(k) + ':' + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (typeof k === 'string') {
                            v = $.toJSON(value[k], whitelist);
                            if (v) {
                                a.push($.toJSON(k) + ':' + v);
                            }
                        }
                    }
                }
                return '{' + a.join(',') + '}';
        }
    };

    })(jQuery);

    //forms
    $("a.submit").click(function() {
        $(this).parents("form:first").submit();
        return false;
    });

    $("form").submit(function() {
        $(this).find("input.watermarked").val("").removeClass("watermarked");
        return true;
    });

    // Enable submit on Enter key
    $("form").append("<input class=\"_submit\" type=\"submit\" value=\".\" style=\"height: 0; width: 0; border: 0; margin: 0; padding: 0; display: inline; opacity: 0;\" />");

    // Tjek for submit links, and fake click on it instead of submitting (for the sake of backwards compatibility)
    $("form a.submit").each(function(i, item) {
        $(item).parents("form:first").find("input._submit").click(function() {
            $(item).click();
            return false;
        });
    });


    //page
    $(".editable").each(function(i, item) {
        $(item).click(function() {
            editPanel = $("#" + $(this).attr("id") + "-edit");
            editable = $(this);

            $(editable).hide();
            $(editPanel).show();
            $(editPanel).find("input[type=text], textarea").eq(0).focus();

            $(editPanel).find(".cancel").click(function() {
                $(editable).show();
                $(editPanel).hide();
                return false;
            });
        });

        if ($(item).attr("title").length == 0)
            $(item).attr("title", "Click to edit");
    });

    // Guestbook
    $("a.delete-tagwall-message").click(function() {
        row = $(this).parent().parent();

        $.get($(this).attr("href"), function(data) {
            if (data.Success) {
                $(row).fadeOut("fast", function() {
                    $(row).find("~ tr").eq(0).remove();
                    $(row).find("~ tr").eq(0).remove();
                    $(row).find("~ tr").eq(0).remove();

                    nextRow = $(row).find("~ tr").eq(0);

                    if ($(nextRow).find("td.replies").size() > 0) {
                        $(nextRow).remove();
                    }

                    $(row).remove();
                });
            }
        });

        return false;
    });

    $("a.replyto-tagwall-message").click(function() {
        $("#replyto-message span").text($(this).parent().find(".tagwall-message-authorname").text() + "'s");

        href = $(this).parent().find("a.replyto-tagwall-message").attr("href");

        $("input#replyid").val(href);
        //		$("input#replyid").val(href.substring(1));

        $("#replyto-message").show("fast");
        $("#comment").focus();

        return false;
    });

    $("a#cancel-tagwall-reply").click(function() {
        $("input#replyid").val("");
        $("#replyto-message").hide("fast");

        return false;
    });


    // Promt

    $.fn.promt = function(isSelfClosing, timeout) {
        $.blockUI(
		{
		    message: $(this),
		    centerY: false,
		    css:
			{
			    position: "absolute",
			    top: "50px",
			    left: ($(window).width() - 538) / 2 + "px",
			    margin: 0,
			    padding: 0,
			    width: "538px",
			    overflow: "hidden",
			    border: "none",
			    cursor: "default",
			    backgroundColor: "transparent"
			},
		    overlayCSS:
			{
			    backgroundColor: "#000",
			    opacity: "0.7"
			}
		});

        $._currentPromt = $(this);

        $('html, body').animate({ scrollTop: 0 }, "fast");
        if (isSelfClosing.toLowerCase() == 'true')
            setTimeout("$('.promt a.close').trigger('click')", timeout);

        return $(this);
    }

    $(".promt a.close").click(function() {
        $.unblockUI();
        $._currentPromt = null;
        return false;
    });

    $(document).keyup(function(e) {
        if ($._currentPromt != null) {
            if ($._currentPromt.length > 0 && e.keyCode == 13) {
                $($._currentPromt).find("a.close").eq(0).click();
            }
        }

    });

    // Updates (temp)

    $("#home-updates td a, #main-user-updates td a").attr("style", "");


    //mouseover list
    $("td.list").mouseover(function() {
        $(this).addClass("active");
    });

    $("td.list").mouseout(function() {
        $(this).removeClass("active");
    });


});






/*********************************FRAMEBOX AND COOKIE PERSISTENCE***************************************/
// Loop over each cookie value and set element CSS accordingly using a mix of jQuery and standard jScript (lbr)
//$(document).ready(function()
//{
//    var frameboxcookie = getCookie('sportzlife-ocbox-cookie');
//    if (frameboxcookie == null) // fix to auto-create cookie
//    {
//        var expDays = 365; // Cookie expiration date
//        var exp = new Date();
//        exp.setTime(exp.getTime() + (expDays*86400000));
//        document.cookie = 'sportzlife-ocbox-cookie="content%20elementShow"; expires="+exp.toGMTString()+ ";path=/';
//        frameboxcookie = getCookie('sportzlife-ocbox-cookie');
//    }
//    var names = frameboxcookie.split("&");

//    for ( var i in names )
//    {
//         var splitter = names[i].split("=");
//         $("#" + names[i].substring(0, splitter[0].length)).addClass(names[i].substring(splitter[0].length + 1));
//         
// 	     //alert(names[i].substring(0, splitter[0].length));
// 	     //alert(names[i].substring(splitter[0].length + 1));
//    }
//});

///* Collapsible fields */
//function toggleClass(eId) 
//{
//	curClass = document.getElementById(eId).className;
//	baseName = ""; //className uden Show eller Hide
//	if (curClass.lastIndexOf("Hide") > -1) 
//	{
//		arrClassName = curClass.split("Hide");
//		postfix = "Show";
//	}
//	else if (curClass.lastIndexOf("Show") > -1) 
//	{
//		arrClassName = curClass.split("Show");
//		postfix = "Hide";
//	}

//	baseName = arrClassName[0];
//	className =  baseName + postfix
//	document.getElementById(eId).className = className;
//	return className;
//}

/* Handle cookies */
// Get the control CSS and save it to a multivalue cookie:
//function saveToMultiValueCookie(objSender, cookieName)
//{
//      // alert(" ID:" + objSender.getAttribute("id") + "   Class:" + objSender.className + "   cookieName:" + cookieName);
//      setMultiValueCookie(cookieName, objSender.getAttribute("id"), objSender.className); // objSender.className works in all browsers (instead of getAttribute)
//}

//function setMultiValueCookie(cookie, name, value)
//{
//    var cookieValue;
//    var expDays = 365; // Cookie expiration date
//    var exp = new Date();
//    exp.setTime(exp.getTime() + (expDays*86400000));
//    var aKeyValues;
//    var aNewKeyValues = Array();
//    var item;
//    var nLen = name.length;
//    var i, found;
//    cookieValue = getCookie(cookie);
//    if (cookieValue != null)
//    {
//        found = false;aKeyValues = cookieValue.split("&");
//        for (i = 0; i < aKeyValues.length; i++)
//        {
//            if (aKeyValues[i].substring(0,nLen+1) == name+"=")
//            {
//                if (value != null) {aNewKeyValues.push(escape(name)+"="+escape(value));
//                found = true;
//            }
//            } 
//            else 
//            {
//                aNewKeyValues.push(aKeyValues[i])
//            }
//        }

//        if (found == false && value != null)
//            aNewKeyValues.push(escape(name)+"="+escape(value));
//            cookieValue = aNewKeyValues.join("&")
//    }
//    else if (value != null)
//    {
//        cookieValue = escape(name)+"="+escape(value)
//    }

//    if (cookieValue != null)
//        document.cookie = cookie+"="+cookieValue+";expires="+exp.toGMTString()+ ";path=/";
//}

//function getCookieVal(offset)
//{
//    var endstr = document.cookie.indexOf(";", offset);
//    if (endstr == -1)
//    endstr = document.cookie.length;
//    return unescape(document.cookie.substring(offset, endstr));
//}

//function getCookie(name)
//{
//    var arg = name + "=";
//    var alen = arg.length;
//    var clen = document.cookie.length;
//    var i = 0;
//    while (i < clen) 
//    {
//        var j = i + alen;
//        if (document.cookie.substring(i, j) == arg)
//        return getCookieVal (j);
//        
//        i = document.cookie.indexOf(" ", i) + 1;
//        if (i == 0) 
//        break;
//    }
//    return null;
//}
/*********************************FRAMEBOX AND COOKIE PERSISTENCE END***************************************/



/*********************************DROPDOWN SELECT, CLEAR AND POPULATE***************************************/
$.fn.clearSelect = function() {
    //alert("clearSelect");
    return this.each(function() {
        if (this.tagName == 'SELECT')
            this.options.length = 0;
    });
 }

// jQuery style fill (used by AdvancedSearch.aspx)
 $.fn.fillSelect = function(data) {
     //alert("fillselect: " + this.name + " " + this.length);
     
     return this.clearSelect().each(function() {
         
         if (this.tagName == 'SELECT') {
             var dropdownList = this;
             $.each(data, function(index, optionData) {
                 var option = new Option(optionData.Text, optionData.Value);

                 if ($.browser.msie) {
                     dropdownList.add(option);
                 }
                 else {
                     dropdownList.add(option, null);
                 }
             });
         }
     });
 }
 
// JavaScript style fill with jQuery flavor (used by AdvancedSearchMap.aspx) 
 function customFillSelect(objSelect, data)
 {
      ClearDropDown(objSelect);
      
      $.each(data, function(index, optionData) {
                 var option = new Option(optionData.Text, optionData.Value);

                 if ($.browser.msie) {
                     objSelect.add(option);
                 }
                 else {
                     objSelect.add(option, null);
                 }
       });
 }

// Clear drop down
function ClearDropDown(ddl)
{
   var len = ddl.options.length;
   for (i=0; i < len; i++)
   {
      ddl.remove(0);
   }
   
   //alert(ddl.length);
}
/*********************************DROPDOWN SELECT, CLEAR AND POPULATE END***************************************/


//submit on enter
//$(document).ready(function() {
//    $("input").keypress(function(e) {
//        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
//            this.form.submit();
//            return false;
//        } else {
//            return true;
//        }
//    });
//    $("textarea").keypress(function(e) {
//        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
//            this.form.submit();
//            return false;
//        } else {
//            return true;
//        }
//    });
//});

//tooltip (requires <div id="tooltip" style="background: #FFFF99; display: none; width: somewidth; height: someheight; color: black;">tooltip text</div>) 
//     and onmousemove="ToggleTooltip(event, targetdivid);" onmouseout="ClearTooltip();" in target div tag.
var tooltipIsVisible = false;
var tooltipIsInitialized = false;
var tooltiptimer;

function ToggleTooltip(e, targetDivID) {
    if (!tooltipIsInitialized) {
        InitTooltip(targetDivID);
    }

    if (!tooltipIsVisible) {
        if (tooltiptimer != null) {
            clearTimeout(tooltiptimer);
        }
        tooltiptimer = setTimeout("ShowTooltip();", 2000);
    }
    else {
        HideTootip();
    }
}

function InitTooltip(targetDivID) {
    var div = document.getElementById('tooltip');
    var mapDiv = document.getElementById(targetDivID);
    div.style.position = 'absolute';

    div.style.top = mapDiv.style.top;

    var absLeft = 0;
    var o = mapDiv;

    var className = mapDiv.parentNode.parentNode.parentNode.className;

    if (className == "box promt") {
        absLeft = 22;
    }
    else {
        while (o != null) {
            absLeft += o.offsetLeft;
            o = o.offsetParent;
        }
    }

    div.style.left = absLeft;

    div.style.zIndex = 2;
    tooltipIsInitialized = true;
}

function ClearTooltip() {
    clearTimeout(tooltiptimer);
}

function ShowTooltip() {
    $("div#tooltip").show('slow');
    tooltipIsVisible = true;
}

function HideTootip() {
    $("div#tooltip").hide('fast');
    tooltipIsVisible = false;
}


