﻿
/**** COOKIE OBJECT ****/
//Object stores all information about sidebar from cookie
var CookieObject =
{
    "orderBoxesSideBar": undefined,
    "collapsedBoxesSideBar": undefined

};
/**** END COOKIE OBJECT ****/

var CookieCP = {

    SET_COOKIE_EXPIRY: 7,
    SIDEBAR_SETTINGS_COOKIE: "cp_sbsett",

    LoadCookie: function() {
        var cookie = jQuery.cookie(this.SIDEBAR_SETTINGS_COOKIE);

        if (!cookie) return;

        CookieObject["orderBoxesSideBar"] = jQuery.evalJSON(cookie).orderBoxesSideBar;
        CookieObject["collapsedBoxesSideBar"] = jQuery.evalJSON(cookie).collapsedBoxesSideBar;
    },

    SaveCookie: function() {
        var encoded = jQuery.toJSON(CookieObject);
        jQuery.cookie(this.SIDEBAR_SETTINGS_COOKIE, encoded, { expires: this.SET_COOKIE_EXPIRY, path: "/" });
    },

    DeleteCookie: function() {
        jQuery.cookie(this.SIDEBAR_SETTINGS_COOKIE, null);
    },

    setCollapsedBoxes: function(collapsedBoxes) {
        CookieObject["collapsedBoxesSideBar"] = collapsedBoxes;
        this.SaveCookie();
    },

    setOrderBoxes: function() {
        CookieObject["orderBoxesSideBar"] = jQuery(SideBar.ID).sortable("toArray");
        this.SaveCookie();
    }

};

/**** textbox watermark ****/
function BlurText() {
//    jQuery("#searchForm1_tbSearchInput").data("defaultValue",$("#searchForm1_tbSearchInput").val()).bind("focusin focusout", function() {
//        var defVal = ($(this).val() == $(this).data("defaultValue")) ? "" : $(this).val();
//        $(this).toggleClass("watermarkOn").val(defVal.toString());
//    });
}
/**** textbox watermark ****/

/**** notification on page ****/
function DisplayMessageOnPage(msg, type) {
    var list = document.createElement("ul");
    list.setAttribute("id", "notifications");

    var message = document.createElement("li");
    message.setAttribute("class", type);
    message.appendChild(document.createTextNode(msg));
    list.appendChild(message);
    $("#content")[0].insertBefore(list, $("#content > *")[0]);

    jQuery('#message').val('');
    jQuery("#subject").val('');
    jQuery('.facelist li').not('li:last').remove();
    jQuery('#result_list ul').remove();
    jQuery('#to_users').val('');
}


/**** notification to Growl ****/
/**** uses the old notifs as data ****/
function showGrowl() {
    if(jQuery("ul#notifications li").length > 0) {
        jQuery("ul#notifications li").each(function(e){
            var klasse = jQuery(this).attr("class");
            var optz;
            switch (klasse) {
                case "success":
                    optz = { life: 10000, sticky: false, theme: klasse, animateOpen: {opacity: 'show', marginTop: '-=25px'}};
                    break;
                case "hint":
                    optz = { sticky: true, theme: klasse, animateOpen: {opacity: 'show', marginTop: '-=25px'} };
                    break;
                case "error":
                    optz = { sticky: true, theme: klasse, animateOpen: {opacity: 'show', marginTop: '-=25px'} };
                    break;
                default:
                    optz = { sticky: true, theme: klasse, animateOpen: {opacity: 'show', marginTop: '-=25px'} };
                    break;
            }
            jQuery.jGrowl(jQuery(this).remove("a.closebutton").html(), optz);        
        });
    }
}

/******* hide success notifications automatically *******/
function NotificationSuccessFadeOut(timer) {
	if(!timer) var timer = 7000;
    $('#notifications li.success').each(function(e){
        $(this).delay(timer).fadeOut(800);
    });
}
/**** notification on page ****/

/***** MAIN ****/
jQuery(document).ready(
	function () {

	    //CookieCP.DeleteCookie();
	    CookieCP.LoadCookie();

	    // var is set from includes/common/searchForm.ascx
	    SideBar.Init();
	    BlurText(searchFormASCXInputText);
	    NotificationSuccessFadeOut();
	    // bind EndRequestHandler to MS Crap
	    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

	    $('#ctl00_content_section_ddlAnswersCount').slider('option', 'step', 8);

	    activateHiliter();
	    traverseLink(".marketlist span.desc");
	    hoverOnLongOptions(".marketlist div.result", ".option");
	    showHint();
	    fakeRadioCheck();
	    commentBoxArrowHiliter();
	    var clicked = 0;
	    // tip of the day widget
	    $(".tipoftheday a.nextTOTD").live("click.totd", function () {
	        if (clicked == 0) {
	            clicked = 1;
	            $(".tipoftheday .tipps:first").clone().insertAfter(".tipoftheday .tipps");
	            $(".tipoftheday .tipps:last").css({ display: "none" })
                 .find("h5").html($("div.nextTippCache span.totd-h5").html())
                 .next("h3").html($("div.nextTippCache span.totd-h3").html())
                 .next("p").html($("div.nextTippCache span.totd-p").html())
                 .next("div").find("a.nextTOTD").css({ display: "none" });
	            $(".tipoftheday .tipps:first").fadeOut(600, function (element) {
	                $(".tipoftheday .tipps:last").fadeIn(350);
	                __doPostBack($('div.nextTippCache input.totd-clientId').val(), $("div.nextTippCache span.totd-numero").text());
	                $(this).remove();
	                setTimeout(function () {
	                    $(".tipoftheday .tipps:visible a.nextTOTD").fadeIn(500);
	                    clicked = 0;
	                }, 500);
	            });
	        }
	    });

	    // tooltipp for trophies
	    $(".TLUser .trophylist img").fadeTipp({
	        tipp: "#fadetipp.trophytipp",
	        copyclass: false,
	        copyfrom: "rel",
	        tippoffset: -110,
	        stayonhover: true
	    });
	    $("ul.actions li input").live("click", function (e) { // loader on friends request
	        $(this).attr({ src: "/images/leer.gif", width: 16, height: 16 }).addClass("loading16");
	    });
	    $("a.refuseFriendship, a.requestFriendship").live("click", function (e) { // loader on send friends request/become friends
	        $(this).addClass("loading16left");
	    });
	    $("ul.commentlist input:submit, .message input:submit, .messageeditor input:submit").live("click", function (e) { // loader on comment, shout & message
	        $(this).addClass("loading16gray");
	    });
	    $(".messagelist input.reply").live("click", function (e) { // loader on comment, shout & message
	        $(this).css("width", $(this).width()).val("   ").addClass("loadingBarGray");
	    });
	    $("ul.sorting li a").live("click", function (e) { // loader on sorting
	        $(this).parents("ul").parent().addClass("loading16top");
	    });
	    var $pagingCont = $("#content ul.paging li a");
	    $pagingCont.live("click", function (e) { // loader on sorting
	        // $(this).parents("ul").parent().prev("div").addClass("loading16top");
	        $(this).parents("ul").prev("table:not(.messagelist)").addClass("loading16");
	        $("#content h4:not(#marketcomments), #content .h4").addClass("loading16");
	        $(this).parents("#content").find("#marketcomments").addClass("loading16");
	        //$(this).parents("ul").prev("ul").addClass("loading16");
	    });
	    var $pagingSide = $("#sidebar ul.paging li a");
	    $pagingSide.live("click", function (e) { // loader on sorting
	        // $(this).parents("ul").parent().prev("div").addClass("loading16top");
	        $(this).parents("ul").prev("table:not(.messagelist)").addClass("loading16");
	        $(this).parents(".widget-content").find("table, .watchTable").addClass("loading16");
	        //$(this).parents("ul").prev("ul").addClass("loading16");
	    });
	    var $pagingHistory = $(".tradeHistory ul.paging li a");
	    $pagingHistory.live("click", function (e) { // loader on sorting
	        $(this).parents(".tradeHistory").find("h5").addClass("loadingline");
	    });




	    showGrowl();
	    permalinkShare();

	    var ScrollTop;
	    $(".tradeHistory h5 a").live("click", function () {
	        if ($(this).parent().hasClass("closed")) {
	            ScrollTop = Number($("body").find(".tradelist").height()) / 2;
	            $(this).parent().removeClass("closed").addClass("opened").parent().find(".klapper").slideDown(function () {
	                $("html").scrollTop(Number($(window).scrollTop()) + ScrollTop);
	            });


	        } else {
	            $(this).parent().removeClass("opened").addClass("closed").parent().find(".klapper").slideUp(function () {
	                $("html").scrollTop(Number($(window).scrollTop()) - ScrollTop);
	            });
	        }
	    });

	    $("#content .linkedAccounts .settings a").live("click", function () {
	        var dis = $(this).parent();
	        dis.find("ul").slideToggle("fast", function () { dis.toggleClass("open"); });
	    });

	    if (('placeholder' in document.createElement('input')) == false) {
	        $("input.placeholder").each(function () {
	            $(this).addClass("tGray").val($(this).attr("placeholder")).focus(function () {
	                if ($(this).val() == $(this).attr("placeholder"))
	                    $(this).val("").removeClass("tGray");
	            }).blur(function () {
	                if ($(this).val() == "")
	                    $(this).val($(this).attr("placeholder")).addClass("tGray");
	            });
	        });
	    }
	    $('textarea').not(".challengeTbl textarea, .ui-  textarea").autogrow();
	    MiniMarketRotationTop.init();
	    $(window).unload(function () { // Safari Highcharts crash bug fix
             $(".highcharts-container").remove();
	    });

	});
/***** END MAIN ****/

// error message fader
	jQuery("input.error, textarea.error").live("keypress", function(e){
		jQuery(this).removeClass("error").parent()
		.find("div.errormsg").slideUp(800);
	});
//	jQuery("input.error:checkbox").live("change", function(e){
//		jQuery(this).removeClass("error").parent().parent()
//		.find("div.errormsg").slideUp(800);
//	});

	jQuery("select.error").live("mouseup", function(e){
		jQuery(this).removeClass("error").parent()
		.find("div.errormsg").slideUp(800);
	});

// handles event callbacks from MS ajax calls
function EndRequestHandler(sender, args) {
	if (args.get_error() == undefined) {
		// NotificationSuccessFadeOut(10000);
        showGrowl();
		if ($("#userList") && $("#userList").length > 0) { // check if autocomplete User List field exists
			fcbkuserlistinit();
		}
	    $("script#netCallback").appendTo("body");
		activateHiliter();
		hoverOnLongOptions(".lstContracts .q .qBox", "span");
        hoverOnLongOptions(".marketlist div.result",".option");
		// if ($("#slAnswersCount").length) { countSlider("#slAnswersCount"); }
        if($(".tradelist td input.cashout").length) $(".tradelist td input.cashout").fadeTipp();
        $("#content h4, #content .h4").removeClass("loading16");
        $(".tradeHistory h5").removeClass("loadingline");
        $(".widget-content").find("table, .watchTable").removeClass("loading16");
	} // else alert("There was an error" + args.get_error().message);
}


// function countSlider(elem) {	
// 	$(elem).slider({value: 0, min: 0, max: 6, animate: true}
// 	).bind('slidechange', function(event, ui) {
// 		$("#ctl00_content_section_ddlAnswersCount").children("option").removeAttr("selected").parent().children("option:eq(" + ($(this).slider("value")) + ")").attr("selected","selected");
// 	});;
// }

//  HILITE The Labels
function activateHiliter() {
    $("input, textarea, select, ul.holder").live("focus", function(e){
        $(this).parents("tr").children("th").children("label").addClass("selected");
        $(this).prev(".nbrs").addClass("selected");
    });
    $("input, textarea, select, ul.holder").live("blur", function(e){
        $(this).parents("tr").children("th").children("label").removeClass("selected");
        $(this).prev(".nbrs").removeClass("selected");
    });
    //fake form (market edit) focus on click
    $(".fakeform .marketeditor .descedit").bind("click", function(e){ 
        $(this).addClass("focus").children("textarea").focus();
    });
    
    $(".fakeform .marketeditor .descedit textarea").bind("focus", function(e){ 
        $(this).parents(".descedit").addClass("focus");
    }).bind("blur", function(e){ 
        $(this).parents(".descedit").removeClass("focus");
    });

	$("input:checkbox, input:radio").bind("click", function(e){
		$(this).parent().parent().children("div.errormsg").children().slideUp(800);
	});
}

// open Password recovery box'

function passRecovShow(e) {

    $('#content_section_panRecovery').slideToggle().toggleClass('active');
    $(e).toggleClass('active');
}

function traverseLink(pfad) {
    $(pfad).each(function(pfad){
        src = $(this).find("a").attr("href");
	    $(this).wrap("<a href='"+ src +"'></a>");
    });
}

// check if option is longer than the box surrounding it
// if so add tooltip functionallity on hover
// (height divided by 1.5 to avoid unwanted tooltips)
function hoverOnLongOptions(pfad, kind) {
    $(pfad).each(function(){
       if(eval($(this).find(kind).outerHeight() / $(this).outerHeight()) > 1.2) {
            $(this).addClass("isLongOpt").prepend("<div class='dots'>&#8230;</div>");
       }
    });
    
    $(".isLongOpt").live("mouseover mouseout", function(e) {
          if (e.type == 'mouseover') {
            $(this).addClass("showOption");
            if(pfad==".qBox") // exception TI
               $(this).parents("tbody").addClass("showCashout") 
        } else {
            $(this).removeClass("showOption");
                if(pfad==".qBox") // exception TI
                   $(this).parents("tbody").removeClass("showCashout") 
        }               
    });    
}

function showHint(pfad) {
	if(pfad==null) pfad = "span.hint";
	$(pfad).prev().hover(function(){
		$(this).next(".hint").show();
	},
	function(){
		$(this).next(".hint").hide();
	});
}
function liHint(pfad) {
	if(pfad==null) pfad = "li.hint";
	$(pfad).parent("ul").hover(function(){
		$(this).find(".hint").show();
	},
	function(){
		$(this).next(".hint").hide();
	});
}


jQuery.fn.log = function (msg) { // extend jQuery with firebug log 
    if(("console" in window) || ("firebug" in console)) {
       console.log("%s: %o", msg, this);
        return this;
    }
 };
 
function fakeRadioCheck() {  // global checkbox replacement
		
		$("input:checkbox").not(".noFake").each(function(){
			// set faker class and add fake checkbox span including input state
			var checkd = $(this).attr("checked") ? "checked" : "";
			$(this).addClass("checkboxhide").after("<span class='fakecheckbox "+checkd+"'>&#32;</span>"); 
		});
        // make fake checkbox clickable
        $(".fakecheckbox").live("click", function() { 
             // if checked then remove checked from both elements
                if($(this).hasClass("checked")) {
                    $(this).removeClass("checked").prev().removeAttr("checked");
                } else {
                    $(this).addClass("checked").prev().attr("checked","checked");
               }
        });
        $("input:radio:not(#accordion h3 input:radio)").each(function(){
            var radiod = $(this).attr("checked") ? "checked" : "";
            $(this).addClass("radiohide").after("<span class='fakeradio "+radiod+"'>&#32;</span>"); 
        });
        // make fake radio button clickable
        $(".fakeradio").live("click", function() { 
             // if checked then remove checked from both elements
                if($(this).hasClass("checked")) {
                    // $(this).removeClass("checked").prev().removeAttr("checked");
                } else {
                    $('input:radio[name=' + $(this).prev().attr("name") + ']:checked').next().removeClass("checked");
                    $(this).addClass("checked").prev().attr("checked","checked");
               }
        });
//         $(":radio").change(function(e){
//             $(this).parent().children(":radio:checked").removeClass("checked");
//              $(this).next(":radio").addClass("checked");
//         });
}

// function beginRequestHandler(sender,args){
//     var elemId = args.get_postBackElement().id;
//     $("#content .mls ul.sorting li").remove(".loadermini");
//    console.log("onBeginRequest on element"+elemId);
//     $("#"+elemId).parent("li").parent("ul").parent("div").children("ul.sorting").remove("li.loadermini").prepend('<li class="loadermini"><div>&#32;</div></li>');
// }
// function endRequestHandler(sender,args){
//     var elemId = args.get_postBackElement().id;
//    console.log("\r onEndRequest on element"+elemId);
//     $("#"+elemId).parent("li").parent("ul").parent("div").children("ul.sorting").remove("li.loadermini");
// }

function commentBoxArrowHiliter() {
    $(".commentlist li textarea").focus(function(){ 
        $(this).prev(".commentarrow").addClass("focus");
    }).blur(function(){
        $(this).prev(".commentarrow").removeClass("focus");
    }).live("keypress", function(e){
    	if(jQuery(".commentlist .commentarrow").hasClass("error")) {
			jQuery(".commentlist .commentarrow").removeClass("error").addClass("focus");
			commentBoxArrowHiliter();
		}
    });
    $(".commentlist li textarea:focus").addClass("focus");
}

function Trenner(n) {
    n += '';
    if ((n.length > 3 && n > 0)||(n<0 && n.length > 4)) {
        var mod = n.length % 3;
        var output = (mod > 0 ? (n.substring(0,mod)) : '');
        for (i=0 ; i < Math.floor(n.length / 3); i++) {
            if ((mod == 0) && (i == 0))
                output += n.substring(mod+ 3 * i, mod + 3 * i + 3);
            else
                output+= '.' + n.substring(mod + 3 * i, mod + 3 * i + 3);
        }
        return (output);
    }
    else return n;
}

function permalinkShare(p) {
	if(!p) var p = "a.permaLink";
	$(p).each(function(event){
		$(this).attr("title","Link zu dieser Seite hier. Klicken Sie für die Adresse.").click(function(event){
			$(this).hide().parent().append("<input class='permaReplace' type='text' value='" + $(this).attr("href") + "' />").focus();
			$("input.permaReplace").select().one("mouseout", function(){
				$(this).parent().children("a").show().next().remove();
			}).live("click",function(e){
				$(this).focus().select();
			});
			return false;
		});
	});
}

function placeholder(inputz){
    var inputz = (inputz) ? inputz : "input[type=text], input[type=password]";
    if(('placeholder' in document.createElement('input')) == false) {
        $(inputz).each(function(){
            $(this).addClass("tGray").val($(this).attr("placeholder"));
        });
        $(inputz).focus(function(){ 
            if($(this).val() == $(this).attr("placeholder"))
                $(this).val("").removeClass("tGray"); 
        });
    }
}
// remove multiple, leading or trailing spaces
function trim(s) {
    s = s.replace(/(^\s*)|(\s*$)/gi, "");
    s = s.replace(/[ ]{2,}/gi, " ");
    s = s.replace(/\n /, "\n");
    return s;
}

var MiniMarketRotation = function (container, items, speed) {
    var container = (container) ? container : "ul.MiniMarketRotation",
        items = (items) ? items : "li",
        wrapperClass = "MiniMarketRotationContainer",
        wrapper = '<div class="' + wrapperClass + '"/>',
        itemWidth = false,
        count = 0,
        itemCount = 0,
        maxHeight = 0,
        speed = (speed) ? speed : 5000;
    $(container).wrap(wrapper).find(items).each(function (event) {
        itemWidth = $("." + wrapperClass).outerWidth();
        $(this).css({ width: itemWidth, display: "block" });
        count++;
        maxHeight = ($(this).height() > maxHeight) ? $(this).height() : maxHeight;
    });
    $(container).css("width", count * itemWidth).parent().css({height: maxHeight});
    var rotation = setInterval(function () {
        itemCount = (itemCount + 1 < count) ? itemCount + 1 : 0;
        $(container).animate({ opacity: "0.7" }, 100, function () {
            $(this).animate({ left: "-" + itemWidth * itemCount }, 500, "swing", function () {
                $(this).animate({ opacity: "1" },100);
            });
        });
    }, speed);
}

var MiniMarketRotationTop = new Object;

MiniMarketRotationTop.init = function(container, items, speed) {
    var container = (container) ? container : "ul.MiniMarketRotation",
        items = (items) ? items : "li",
        speed = (speed) ? speed : 5000,
        wrapperClass = "MiniMarketRotationContainer",
        wrapper = '<div class="' + wrapperClass + '"/>',
        itemheight = false,
        sumHeight = 0,
        maxHeight = 0,
        count = $(container + " " + items).length,
        itemCount = 0;
    $(container).wrap(wrapper).find(items).each(function (event) {
        $(this).children("div").append('<span class="banner">Mitsetzen!</span>');
        sumHeight += $(this).outerHeight(true);
        maxHeight = ($(this).height() > maxHeight) ? $(this).height() : maxHeight;
    });

    $(container).css("height", sumHeight).parent().css("height", maxHeight).find(items).css({ height: maxHeight, display: "block" });
    
    var rotation = window.setInterval("MiniMarketRotationTop.tues()", speed);
    this.tues = function(pos){
        if(!MiniMarketRotationTop.mover) {
        itemCount = (pos) ? pos : (itemCount + 1 < count) ? itemCount + 1 : 0;
        var h = $(container + " " + items + ":eq(" + (itemCount) + ")").outerHeight(true);
        var itemH = (itemCount == 0) ? 0 : "-=" + (h);
        $(container).animate({ opacity: "0.6" }, 300)
           .animate({ top: itemH }, speed/4, "swing", function () {
                $(this).animate({ opacity: "1" }, 100);
            });
        }
    }
    $(container).find(items).mouseover(function(){
        MiniMarketRotationTop.mover = true;
    }).mouseout(function(){
        MiniMarketRotationTop.mover = false;
    }).find(".banner").click(function(){
        $(document)
    });
    this.mover = false;

}
 
function regQtw(origin)
{
	$('input.qtrade').attr('disabled', true);
	var $this = $(origin);
	var QTrel = $this.attr("rel");
	var QTval = ($this.parent().prev().children('input.betVal').val()) ? $this.parent().prev().children('input.betVal').val() : null;
	$.ajax({
		url: '/DataService/WidgetService.svc/quicktrade/',
		data: '{"call": "' + QTrel + '", "betvalue": "' + QTval + '"}',
		type: 'POST',
		processData: false,
		contentType: 'application/json; charset=utf-8',
		timeout: 10000,
		dataType: 'json',
		success: function (res) { $this.parents('.quickTradeBox').replaceWith(res); }
	});
}

function injectMessage(type, mess)
{
	$('ul#notifications').html('<li class="' + type + '">' + mess + '</li>');
	showGrowl();
}



