
// Unisg.FNC
//GLOBAL
var UNISG = window.UNISG || {};


//console.log
function log(text) {
    if (jQuery.browser.mozilla) {
        console.log(text);
    }
}

//Add pseudo-class for IE
jQuery(document).ready(function () {
    if (jQuery.browser.msie) {
        jQuery("p:empty").addClass('isempty');
        jQuery("div:empty").addClass('isempty');
        jQuery('.isempty').remove("p");
    }

    //Add Class for last-Child
    jQuery('#oumanager #maincontent_0_content_2_pnlLeft table td:last-child').addClass('lastChild');

    //Remove empty h3
    jQuery('h3').filter(function () {
        return jQuery.trim(jQuery(this).text()) === '';
    })
     .remove();
    //Remove empty p
    //    jQuery('p').filter(function () {
    //        return jQuery.trim(jQuery(this).text()) === '';
    //    })
    //     .remove();

    //Change fixed width in IE for select dropdown
    jQuery(".scfDropList").mousedown(function () {
        if (jQuery.browser.msie) {
            //jQuery(this).css("width", "auto");
            jQuery(this).css("min-width", "204px");
        }
    });
    jQuery(".scfDropList").change(function () {
        if (jQuery.browser.msie) {
            jQuery(this).css("width", "204px");
        }
    });
    jQuery(".scfDropList").blur(function () {
        if (jQuery.browser.msie) {
            jQuery(this).css("width", "204px");
        }
    });

    //position je nach Höhe des divs setzen - Bug 2949
    if (jQuery(jQuery("#ct_sub_brand_home .faux_line > div#ct_inst_home_main_with_context")[0]).height() < jQuery(jQuery("#ct_sub_brand_home .faux_line > div#ct_inst_home_context")[0]).height()) {
        if (jQuery.browser.msie && jQuery.browser.version <= 7) {
            jQuery("div#ct_inst_home_main_with_context").css("position", "relative");
            jQuery("div#ct_inst_home_context").css("position", "");
        }
        else {
            $("div#ct_inst_home_main_with_context").css("position", "absolute");
            $("div#ct_inst_home_context").css("position", "relative");
            $("div#ct_inst_home_context").css("margin-left", "46.1em"); //joz, context div hätte sich sonst mit dem hauptdiv der institute überlappt

        }
    }

});

function redirectInst() {
    var selector = "#" + this.event.srcElement.id + " option:selected";
    var url = jQuery(selector).val();

    //Falls keine Url übergeben wird (zB. "Select Institute...") --> verhindere den redirect, ansonsten ---> 404
    if (url == "" || url == "undefined")
        return false;

    if (url.valueOf("http") < 0) {
        // die urls beziehen sich nur auf die institute http://www.ABC.unisg.ch
        url = "http://" + url;
    }
    window.open(url);
    //window.open("http://www.item.unisg.ch");
}


/*
Redirect selector class:
if this class is appended to a Combobox (DropdownList, ...), the Combobox acts as an redirector selector
*/
jQuery(document).ready(function () {
    jQuery(".redirectSelector").change(function (e) {
        var selector = "#" + this.id + " option:selected";
        var url = jQuery(selector).val();

        //Falls keine Url übergeben wird (zB. "Select Institute...") --> verhindere den redirect, ansonsten ---> 404
        if (url == "" || url == "undefined")
            return false;

        var isLocal = url.substr(0, 1) == "/";
        if (isLocal) {
            window.location.href = url;
        }
        else {
            if (url.valueOf("http") < 0) {
                // die urls beziehen sich nur auf die institute http://www.ABC.unisg.ch
                url = "http://" + url;
            }
            window.open(url);
            //window.open("http://www.item.unisg.ch");
        }
    });
});

// Formular Pflichtfeldermarkierung überall nach dem Label setzen, IE7 machte dies nicht sauber //
jQuery(document).ready(function () {
    jQuery('div.scfSectionContent > div').each(function (index) {
        jQuery('> span.scfRequired', jQuery(this)).appendTo(jQuery('> label', jQuery(this)));
    });

    jQuery('div.scfSectionContent > div').each(function (index) {
        jQuery('> span.scfValidatorRequired', jQuery(this)).appendTo(jQuery('> label', jQuery(this)));
    });
});

// Search Handler //
jQuery(document).ready(function () {
    jQuery(".globalSearchMarkerTextbox").keydown(function (e) {
        var keyCode = e.keyCode;
        var eventSource = jQuery("#" + this.id);
        if (keyCode == 13) { //enter: jump to href
            if ((eventSource.val() == "") || (eventSource.val() == "undefined")) {
                eventSource.css("background-color", "lightgray");
                eventSource.focus();
                return (false);
            }
        } else {
            eventSource.css("background-color", "white");
        }

        return (true);
    });
    jQuery(".globalSearchMarkerSubmit").click(function (e) {

        var postback = false;


        //Enumerate all searchInput fields, find first field with value --> need postback    
        jQuery(".globalSearchMarkerSubmit").each(function (e) {
            var eventSourceId = "#" + this.id;

            if (!eventSourceId)
                return (false);
            else
                eventSourceId = "#" + this.id.replace("search_btn", "fulltext_search_input");

            var eventSource = jQuery(eventSourceId); // jQuery(".globalSearchMarkerTextbox");
            if ((eventSource.val() == "") || (!eventSource.val())) {
            } else {
                postback = true;
            }
        });

        if (!postback)
            jQuery(".globalSearchMarkerSubmit").each(function (e) {
                var eventSourceId = "#" + this.id;

                if (!eventSourceId)
                    return (false);
                else
                    eventSourceId = "#" + this.id.replace("search_btn", "fulltext_search_input");

                var eventSource = jQuery(eventSourceId); // jQuery(".globalSearchMarkerTextbox");
                if ((eventSource.val() == "") || (!eventSource.val())) {
                    eventSource.css("background-color", "lightgray");
                    eventSource.focus();
                }
            });
        return (postback);

    });


    jQuery(".txtLogin").keydown(function (e) {
        var keyCode = e.keyCode;
        var postback = true;
        var firstEmptyControl;
        jQuery(".txtLogin").each(function (e) {
            if (keyCode == 13) {
                jQuery("#" + this.id + "Required").css("visibility", "hidden");

                if ((jQuery(this).val() == "") || (jQuery(this).val() == undefined)) {
                    postback = false;
                    jQuery("#" + this.id + "Required").css("visibility", "");
                    if (!firstEmptyControl)
                        firstEmptyControl = jQuery(this);

                }

            }

        }

        );
        if (firstEmptyControl)
            firstEmptyControl.focus();

        if (keyCode == 13) {
            if (postback) { //enter: jump to href
                jQuery(".btnLogin").click();
            } else
                return (false);
        }
    });
});

jQuery(document).ready(function () {
    var timer;
    var slideCount = 0;
    var next = 0;
    var slideTimeout = "5000";
    var opacityTimeout = 1000;

    OnSlideShowLoad();

    function changeSlide(event) {

        if (next >= slideCount) next = 0;
        var rotImage = $("#image" + next);
        var rotImageText = $("#text" + next);
        var rotImageHeadline = $("#headline" + next);
        var btnAnchor = $("#anchor" + next);


        $(".slide").css("visibility", "hidden");
        $(".slideText").css("visibility", "hidden");
        $(".slideHeadline").css("visibility", "hidden");
        $(".slideA").removeClass("active");

        if (btnAnchor != null) btnAnchor.addClass("active");

        if (rotImage != null) rotImage.css("visibility", "visible");
        if (rotImageText != null) rotImageText.css("visibility", "visible");
        if (rotImageHeadline != null) rotImageHeadline.css("visibility", "visible");

        if (rotImage != null) rotImage.css("opacity", "0");
        if (!(jQuery.browser.msie && (jQuery.browser.version == 8 || jQuery.browser.version == 7))) {
            if (rotImageText != null) rotImageText.css("opacity", "0");
            if (rotImageHeadline != null) rotImageHeadline.css("opacity", "0");
        }

        if (rotImage != null) rotImage.animate({ "opacity": 1 }, opacityTimeout, "linear", null);
        if (!(jQuery.browser.msie && (jQuery.browser.version == 8 || jQuery.browser.version == 7))) {
            if (rotImageText != null) rotImageText.animate({ "opacity": 1 }, opacityTimeout, "linear", null);
            if (rotImageHeadline != null) rotImageHeadline.animate({ "opacity": 1 }, opacityTimeout, "linear", null);
        }

        SetTextShadowOnVisual(next);

        clearTimeout(timer);
        timer = setTimeout(eval("next= next + 1; changeSlide"), slideTimeout);

        if (rotImage != null) rotImage.animate({ "opacity": 1 }, opacityTimeout, "linear", null);
        if (!(jQuery.browser.msie && (jQuery.browser.version == 8 || jQuery.browser.version == 7))) {
            if (rotImageText != null) rotImageText.animate({ "opacity": 1 }, opacityTimeout, "linear", null);
            if (rotImageHeadline != null) rotImageHeadline.animate({ "opacity": 1 }, opacityTimeout, "linear", null);
        }
    }

    function SetTextShadowOnVisual(i) {
        if (!(jQuery.browser.msie && (jQuery.browser.version == 8 || jQuery.browser.version == 7))) {
            var text = $("#text" + i);
            var headline = $("#headline" + i);

            var option = { x: 1, y: 2, radius: 3, color: "#000" }

            if (text != null) text.textShadow(option);
            if (headline != null) headline.textShadow(option);
        }
    }
    function OnSlideShowLoad(event) {
        clearTimeout(timer);
        var slideShow = document.getElementById("visualSlideshow");

        if (slideShow != null) {
            SetTextShadowOnVisual(0);

            var slideArray = slideShow.getElementsByTagName("li"); // document.getElementsByClassName("slide"); funktioniert nicht bei IE7
            slideCount = 0;
            for (var slide = 0; slide < slideArray.length; slide++) {
                if (slideArray[slide].className == "slide") {
                    slideCount = slideCount + 1;
                }
            }

            if (slideCount > 1) { //bei slideCount == 0 wurrde der htmlCode bereits in Visual.cs geschrieben

                for (var j = 0; j < slideCount; j++) {
                    var rotImageBtn = $("#visualBtn" + j);
                    if (rotImageBtn != null) {
                        rotImageBtn.bind('click', visualBtnClick);
                    }

                }
                slideTimeout = slideShow.getAttribute("timeout");
                timer = setTimeout(eval("next = 1; changeSlide"), slideTimeout);
            }
        }
    }
    function visualBtnClick(event) {

        clearTimeout(timer);
        var btnID = event.currentTarget.id;
        var idLength = btnID.length - 9; // visualBtn
        var intBtnID = parseInt(btnID.substring(9, 9 + idLength));

        next = intBtnID; //visuals und buttons nummeriert von 1 bis x
        //current = next - 1;  //in der methode changeSlide() wird next berechnet (current+1)   

        changeSlide();
    }

});

/* nke, 12.01.2012 
* opens target url in new window
* targetUrl (string): target url with placeholder for query parameter
* idInputOfParamValue (string): id of input control which holds the value for the query string parameter (for placeholder in 'targetUrl')
*/
function openTargetUrlInNewWindow(targetUrl, idInputOfParamValue) {
    // get input value
    var queryParameterValue = jQuery('#' + idInputOfParamValue).val();
    // format target url
    var url = jQuery.validator.format(targetUrl, queryParameterValue);
    // encode url
    url = encodeURI(url);
    // open url in new window
    window.open(url);
    return false;
}

/* nke, 26.01.2012 
* posts current site to aleph login
* targetUrl (string): target url to post login data
* idInputOfLoginValue (string): id of input control which holds the value for the login
* idInputOfPwdValue (string): id fo input control which holds the value for the password
*/
function postAlephLogin(targetUrl, idInputOfLoginValue, idInputOfPwdValue) {
    // current action of the page form
    var formAction = jQuery('form:first').attr('action');
    // current target of the page form
    var formTarget = jQuery('form:first').attr('target');
    // current method of the page form
    var formMethod = jQuery('form:first').attr('method');

    // switch action of form tag to aleph login page
    jQuery('form:first').attr('action', targetUrl);
    // switch target of form tag to open login in new window
    jQuery('form:first').attr('target', '_blank');
    // switch method of form tag to post
    jQuery('form:first').attr('method', 'post');
    
    // post login data
    jQuery('form:first').submit();

    // switch action back
    jQuery('form').attr('action', formAction);
    // switch target back
    jQuery('form:first').attr('target', formTarget);
    // switch method back
    var formMethod = jQuery('form:first').attr('method', formMethod);

    return false;
}
//End Unisg.Fnc

// Unisg.Init
jQuery(function () {
    //adjust body bg (compensate for now hidden #nojs)
    jQuery("innerBody").css("backgroundPosition", "center 0");

    //focus search field
    jQuery("#search_input").focus();

    //click handler: small font size
    jQuery("#font_s").click(function () {
        UNISG.fontresize(jQuery(this).attr("id"));
        return false;
    });
    //click handler: medium (default) font size
    jQuery("#font_m").click(function () {
        UNISG.fontresize(jQuery(this).attr("id"));
        return false;
    });
    //click handler: large font size
    jQuery("#font_l").click(function () {
        UNISG.fontresize(jQuery(this).attr("id"));
        return false;
    });


    //click handler: print page
    jQuery("a.print").click(function () {
        window.print();
        return false;
    });


    (function (jQuery) {
        jQuery.fn.watermark = function (css, text) {
            return this.each(function () {
                var i = jQuery(this), w;
                i.focus(function () {
                    i.css("background-color", "gray");
                })

            .blur(function () {
                i.css("background-color", "white");
            })

            .closest('form').submit(function () {
                w && i.val('');
            });

                i.blur();
            });
        }
    });


    jQuery("a[rel=#overlay]").overlay({
        mask: {
            color: '#333333',
            loadSpeed: 200,
            opacity: 0.9
        },
        effect: 'apple',

        onBeforeLoad: function () {


            // grab wrapper element inside content
            var wrap = this.getOverlay().find(".contentWrap");
            var href = this.getTrigger().attr("href");

            wrap.attr('src', href);
        }
    });

    jQuery("a[rel=div.overlay]").overlay({

        mask: {
            color: '#333333',
            loadSpeed: 200,
            opacity: 0.9
        },
        effect: 'apple',

        onBeforeLoad: function () {
        },

        // when overlay is opened, load our player
        onLoad: function (content) {
            var href = this.getTrigger().attr("vid");

            this.getOverlay().find("a.videoOverlay").attr("href", href);
            var player = $f("videoOverlay", "/tools/flowplayer-3.2.5.swf");
            player.load();
        },

        // when overlay is closed, unload our player
        onClose: function () {
            var player = $f("videoOverlay", "/tools/flowplayer-3.2.5.swf");
            player.unload();
        }
    });


    jQuery("div[rel]").overlay({

        // some mask tweaks suitable for modal dialogs
        mask: {
            color: '#ebecff',
            loadSpeed: 200,
            opacity: 0.9
        },
        effect: 'apple',
        expose: //'#789'
		({
		    opacity: 0.8,
		    closeSpeed: 'slow'
		}),
        onLoad: function (content) {
            // find the player contained inside this overlay and load it
            this.getOverlay().find("a.player").flowplayer(0).load();
        },

        onClose: function (content) {
            $f().unload();
        }
    });

    // install flowplayers
    // a- tags with class "myPlayer" are transformed into video players
    flowplayer("a.inboundplayer", "/tools/flowplayer-3.2.5.swf", {
        // this is the player configuration. You'll learn on upcoming demos.
        plugins: {
            controls: {
                volume: false
            }
        }
    });

    jQuery(".thickbox").click(function (e) {
        var imgTag = jQuery(this)[0];
        var caption = imgTag.title;
        var src = imgTag.src.replace("/~/contentMedia", "/~/media");
        src = imgTag.src.replace("/~/contentGraphic", "/~/media");
        tb_show(caption, src, "grp1");
    });
});


(function (jQuery) {
    jQuery.fn.commitEmpty = function () {
        alert("Just clicked");
    };
})(jQuery);

(function (jQuery) {
    //var overlayedVideoPlayer = $f("videoOverlay", "/tools/flowplayer-3.2.5.swf\
    jQuery("a.overlayedplayer[rel]").overlay({
        mask: {
            color: '#333333',
            loadSpeed: 200,
            opacity: 0.9
        },
        effect: 'apple',


        onBeforeLoad: function () {
            alert("Before load");
        },

        onLoad: function () {
            var overlayedVideoPlayer = $f("videoOverlay", "/tools/flowplayer-3.2.5.swf");
            overlayedVideoPlayer.load();
        },

        // when overlay is closed, unload our player
        onClose: function () {
            overlayedVideoPlayer.unload();
        }
    });
})(jQuery);
// End Unisg.Init


/*
jQuery(document).ready(function () {

    jQuery.ajax({
        type: "POST",
        data: {},
        dataType: "xml",
        url: "/services/AsyncContentService.asmx/GetAsyncHSGToday",
        success: function (resp, msg) {
            if (resp.text)
                jQuery("#today").html(resp.text);
            else
                jQuery("#today").html(resp.firstChild.textContent);
        }
    });

    jQuery.ajax({
        type: "POST",
        data: {},
        dataType: "xml",
        url: "/services/AsyncContentService.asmx/GetAsyncNewsOverview",
        success: function (resp, msg) {
            if (resp.text)
                jQuery("#news").html(resp.text);
            else
                jQuery("#news").html(resp.firstChild.textContent);
        }
    });
});
*/
