
/* - ++resource++monopol.theme.javascripts/monopol-theme.js - */
function getPageEventCoords(evt) {
    // thanks to o'reilly!
    var coords = {left:0, top:0};
    if (evt.pageX) {
        coords.left = evt.pageX;
        coords.top = evt.pageY;
    } else if (evt.clientX) {
        coords.left =
            evt.clientX + document.body.scrollLeft - document.body.clientLeft;
        coords.top =
            evt.clientY + document.body.scrollTop - document.body.clientTop;
        // include html element space, if applicable
        if (document.body.parentElement && document.body.parentElement.clientLeft) {
            var bodParent = document.body.parentElement;
            coords.left += bodParent.scrollLeft - bodParent.clientLeft;
            coords.top += bodParent.scrollTop - bodParent.clientTop;
        }
    }
    return coords;
}

jq(document).ready(function() {

     // counter for portlet "punkt eins"
     /*if(jq('dl.portletKommentar')) {
         // set to tomorrow 13:00
         var to = new Date();
         var hour = to.getHours();
         if(hour >= 13) {
             to.setDate(to.getDate()+1);
         }
         to.setHours(13);
         to.setMinutes(0);
         to.setSeconds(0);

         jq('.counterpunkteins').countdown({
            labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'],
                // The expanded texts for the counters
            labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'],
                // The display texts for the counters if only one
            compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters
            timeSeparator: ':', // Separator for time periods
            isRTL: false, // True for right-to-left languages, false for left-to-right
            //until: new Date(2009, 0, 10, 13), // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to
            until: to, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to
                // or numeric for seconds offset, or string for unit offset(s):
                // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
            since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up to
                // or numeric for seconds offset, or string for unit offset(s):
                // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
            format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero,
                // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
            layout: '', // Build your own layout for the countdown
            compact: true, // True to display in a compact format, false for an expanded one
            description: '', // The description displayed for the countdown
            expiryUrl: null, // A URL to load upon expiry, replacing the current page
            alwaysExpire: false, // True to trigger onExpiry even if never counted down
            onExpiry: null, // Callback when the countdown expires -
                // receives no parameters and 'this' is the containing division
            onTick: null, // Callback when the countdown is updated -
                // receives int[7] being the breakdown by period (based on format)
                // and 'this' is the containing division
            serverTime: null // The current time on the server,
                // to calculate an offset for other time zones
           }
         );
         //jq('.counterpunkteins').countdown("resume");
       }*/



    // menue mouse over
    /*jq('div.first a.first').mouseover(function(event) {
        jq('div.first').css('background-color', '#036');
        jq('div.first a.first').css('color', '#fff');
    })
    jq('div.first a.first').mouseout(function(event) {
        jq('div.first').css('background-color', '#fff');
        jq('div.first a.first').css('color', '#036');
    })*/


    // Login-Box im Kontext von Aktionen anzeigen, die ein Login erfordern
    // Wir nutzen das form handling und laden deshalb das ganze form nach
    jq('.request-login').click(function(event) {
        event.preventDefault();
        jq('#loginform').load('freitag_login_form', {},  function(){
            jq('#loginbox').removeClass('shrunk').show();
            jq('#__ac_name').focus();
        });
        var coords = getPageEventCoords(event);
        jq('#loginbox').css('top', coords.top+15).css('left',coords.left);
    });

    // Login-Box ausblenden, wenn click ausserhalb
    jq('body').click(function(event){
       var currNode = jq(event.target || event.srcElement)
       if ((currNode.attr('id') != 'loginform' && currNode.parents('#loginform').length==0 && !currNode.hasClass('request-login') && currNode.parents('.request-login').length==0)) {
           jq('#loginbox').hide().addClass('shrunk');
           // jq('#loginform').load('dummy');
           jq('#loginform').text('');
       }
    })


    /* Ressort Navigation */
    jq('#ressort-ressort-menu > li').hover( function() {
        var umenu_id = 'ressort-umenu-' + this.id.split('-')[2];
        jq('.ressort-umenu').hide()
        if (jq('#'+umenu_id).length>0) {
            jq('#'+umenu_id).fadeIn();
            jq('#ressort-umenu').removeClass('border-top').addClass('border-bottom');
        } else {
            jq('#ressort-umenu').removeClass('border-bottom').addClass('border-top');
        }
    },
    function() {
    })


    /* clock */
    var options = {
      /*fontFamily: 'Georgia, "Times New Roman", Times, serif',
      fontSize: '11px'*/
    };
    jq('.jclock').jclock(options);


    /* topbox flash */
    jq('#topbox-flash').removeClass('flash_main_off').addClass('flash_main');
    jq('#topbox-flash-placeholder').hide();
    //        .html("");
    jq('#topbox-flash').flash({
        src: 'preloader.swf',
        width: 561,
        height: 348,
        wmode : "transparent",
        version : 7,
        'z-index': 10,
        flashvars: { preloadTarget: 'teaser1.swf', preloadDocumentClassName: 'Teaser1', preloadInitParams: '0' }
        },
        { expressInstall: true }
        );

    /*jq('#topbox-flash').flash({
        src: 'teaser1.swf',
        width: 561,
        height: 348,
        wmode : "transparent",
        version : 7,
        'z-index': 10,
        flashvars: { config: 'asldkfjasldfkj.xml' }
        },
        { expressInstall: true }
        );*/

    /* lokales googlemaps flash */
    jq('#lokalesbox-flash-placeholder').hide();
    jq('#lokales-flash').flash({
        src: 'preloader.swf',
        width: 875,
        height: 300,
        wmode : "transparent",
        version : 7,
        'z-index': 10,
        //flashvars: { preloadTarget: 'FlashMaps.swf', preloadDocumentClassName: 'FlashMaps', preloadInitParams: '0', requestPath: 'googlemaps.xml', requestParams: escape('?getLocations(view=city&city=berlin&categorie=hotel)') }
        flashvars: { preloadTarget: 'FlashMaps.swf', preloadDocumentClassName: 'FlashMaps', preloadInitParams: '0', requestPath: 'http://freitag.local:8051/freitag/googlemaps.xml', requestParams: escape('?getLocations(view=city&city=berlin&categorie=hotel)') }
        //flashvars: { preloadTarget: 'FlashMaps.swf', preloadDocumentClassName: 'FlashMaps', preloadInitParams: '0' }
        },
        { expressInstall: true }
        );

    // wenn flash nicht installiert ist, dann injiziert jquery.flash ein element mit class ".flash-update"
    // dieses ersetzen wir durch den Platzhalter (Bild)
    // dies ist unsere flash detection
    // TODO version von flash checken
    if (jq('.flash-update').length>0) {
        //restore image for non flash users
        jq('#topbox-flash').hide();
        jq('#topbox-flash-placeholder').show();
    };


    // 1st paragraph of article
    // dont use this - the initiale is set explicitely
    /*jq("#main_text p:eq(0)").each(function(){
    		if(jq.browser.opera) jq(this).wrap("<div class='firstoperap'></div>");
    		else jq(this).wrap("<div class='firstp'></div>");
    	});*/

    // Artikelinfobox in den Content verschieben (vor den drittletzten Absatz)
    var thirdlastparagraph = jq("#main_text p").length - 3
    if (thirdlastparagraph >= 0) {
        thirdlastparagraph = 1;
    }
    if (thirdlastparagraph > 0) {
        //jq("#main_text p:eq("+thirdlastparagraph+")").before(jQuery("#freitag-article-info"))
    }

    /* browser fixes */
    if (jq.browser.msie) {
        // jq('#portal-global-actions').css({'right':'170px', 'top':'-74px'});
        // jq('#ressort-menu').css({'margin-top':'25px'});
        // jq('#ressort-ressort-menu').css({'top':'-23px'});
        // jq('#portal-topbox').css({'height':'290px'});
        // jq('#topbox-flash, #topbox-flash-placeholder').css({'position':'relative','top':'-10px'});
        // jq('#portal-date').css({'top':'-63px'})
    }

    if (jq.browser.opera) {
        // jq('#portal-personalactions').css({'top':'0px'})
        // jq('#portal-personalinfo').css({'top':'8px'})
        // jq('#portal-global-actions').css({'top':'12px'})
        // jq('#portal-date').css({'top':'20px'})
        // jq('#ressort-menu').css({'margin-top':'0px'});
        // jq('#ressort-ressort-menu').css({'top':'0px'});
        // jq('#ressort-umenu').css({'top':'-15px', 'float':'left', 'width': '850px'});
        // jq('#special-menu').css({'top':'-18px'});
        // jq('#topbox-flash, #topbox-flash-placeholder').css({'position':'relative','top':'-10px'});
    }
    if (jq.browser.safari) {
        // jq('#ressort-ressort-menu').css({'top':'-22px'});
        // jq('#ressort-umenu').css({'top':'-40px'});
        // jq('#special-menu').css({'top':'-43px'});
    }


    /* Vorschau */
    jq('#link-morgen').click( function () {
        jq('#vorschau-morgen').show();
        jq('#vorschau-uebermorgen').hide();
    })
    jq('#link-uebermorgen').click( function () {
        jq('#vorschau-uebermorgen').show();
        jq('#vorschau-morgen').hide();
    })


    /* Tooltip */
    
    // jq('a, img, area, label, input').tooltip({
    //     track: true,
    //  delay: 0,
    //  showURL: false,
    //  showBody: " - ",
    //  opacity: 0.85
    // });
    jq('a, img, area, label, input').tooltip();

    // no tooltip
    jq("div#portal-header a, #portal-siteactions a").removeAttr("title");


    /* formatting */
    jq('#relatedItemBox a').prepend('>>');

    jq('#main_text img[title]').each(function() {
        //jq(this).after(' <span class="img-caption>'+jq(this).attr('title')+'</span>').wrap(' <div style="border:solid 2px red"></div>');
        title_text = jq(this).attr('alt');
        if(title_text == '') { title_text = jq(this).attr('title'); }
        jq(this).wrap(' <div class="artikel_content_image captioned-img"></div>').parent().append(' <br />' + title_text);
    });

    /* most commented */
    jq('.community_most .portletFrame').hide();
    jq('#frame-mostcommented-7').show();

    jq('.community_most .frame_link').click(function() {
        var id = this.id;
        var args = id.split('-')
        var value = args[2]
        jq('#community_most_arg_' + args[1]).val(value);

        jq('.community_most .portletFrame').hide();
        var type = jq('#community_most_arg_type').val()
        var delta = jq('#community_most_arg_delta').val()
        jq('#frame-' + type + '-' + delta).show();

        //jq('.frame_link').removeClass('selected')
        jq(this).siblings().removeClass('selected')
        jq(this).addClass('selected')
    })

    /* ressortnews */
    jq('.ressortnews .portletFrame').hide();
    jq('#frame-ressortnews-articles').show();

    jq('.ressortnews .frame_link').click(function() {
        var id = this.id;
        var frameid = id.replace('link', 'frame')

        jq('.ressortnews .portletFrame').hide();
        jq('#'+frameid).show();

        jq(this).siblings().removeClass('selected')
        jq(this).addClass('selected')

        jq('.ressortnews .head').hide();
        var type = id.split('-')[2]
        jq('.ressortnews .head.'+type).show()

    })


    // positionen (positions)
    // (like morelocations)
    jq('positions.batch').hide();
    jq('positions.batch:first').show()
    jq('#down').click(function() {
        args = jq(this).attr('class').split('-');
        var index = args[2];
        jq('.batch').hide();
        jq('#batch-'+index).show();
        down_id = (parseInt(args[2])+1)>parseInt(args[1]) ? '1' : (parseInt(args[2])+1);
        jq(this).attr('class', args[0]+'-'+args[1]+'-'+down_id);
        up_id = (parseInt(args[2])-1)==0 ? args[1] : (parseInt(args[2])-1);
        jq('#up').attr('class', args[0]+'-'+args[1]+'-'+up_id)
    })
    jq('#up').click(function() {
        args = jq(this).attr('class').split('-');
        var index = args[2];
        jq('.batch').hide();
        jq('#batch-'+index).show();
        up_id = (parseInt(args[2])-1)==0 ? args[1] : (parseInt(args[2])-1);
        jq(this).attr('class', args[0]+'-'+args[1]+'-'+up_id);
        down_id = (parseInt(args[2])+1)>parseInt(args[1]) ? '1' : (parseInt(args[2])+1);
        jq('#down').attr('class', args[0]+'-'+args[1]+'-'+down_id);
    })

    // jwysiwyg
    //jq('textarea.comment_text').wysiwyg();
    //jq('div.wysiwyg').css('width', '480px');
    //jq('div.wysiwyg iframe').css('width', '475px');
    //jq('td.comment_right div.wysiwyg').css('margin', '0 0 0 -65px');

    // jwysiwyg nur fuer blogs
    jq('#blogging #body').wysiwyg({
       controls : {
           separator05 : { visible : false },
           separator08 : { visible : false },
           increaseFontSize : { visible : false },
           decreaseFontSize : { visible : false },
           h1mozilla : { visible : false},
           h2mozilla : { visible : false},
           h3mozilla : { visible : false},
           h1 : { visible : false},
           h2 : { visible : false},
           h3 : { visible : false},
           separator06 : { separator : false },
           separator08 : { separator : false },
           separator09 : { separator : false },
           html : {
               visible : true,
               exec    : function()
               {
                   if ( this.viewHTML )
                   {
                       this.setContent( jq(this.original).val() );
                       jq(this.original).hide();
                   }
                   else
                   {
                       this.saveContent();
                       jq(this.original).show();
                   }

                   this.viewHTML = !( this.viewHTML );
               }
           },
           insertImage : {
               visible : true,
               exec    : function()
               {
                   if ( jq.browser.msie )                       
                  {
                      // this.editorDoc.execCommand('insertImage', true, null);
                      var szURL = prompt('URL', 'http://');

                      if ( szURL && szURL.length > 0 )
                          this.editorDoc.execCommand('insertImage', false, szURL);
                  }
                   else
                   {
                       var szURL = prompt('URL', 'http://');

                       if ( szURL && szURL.length > 0 )
                           this.editorDoc.execCommand('insertImage', false, szURL);
                   }
               }
           }
       }
    });
    
    // jq('textarea#body').wysiwyg();
    jq('#blogging div.wysiwyg').css('width', '540px').css('height', '400px');
    // jq('#blogging div.wysiwyg iframe').css('width', '540px');



})

jq.fn.default_input = function() {
    return this.each(function(){
        jq(this).attr('value', jq(this).attr('title'));
        jq(this).focus(function(){
            jq(this).attr('value') = '';
        });
        jq(this).blur(function(){
            var newValue = jq(this).attr('value');
            if (newValue == '') {
                jq(this).attr('value') = jq(this).attr('title');
            }
        });
    });
};

