/**
 * @author Admin
 */

var ProgramGlobal;

function cufonGo()
{
    console.log("cufon go");

    var cufon;
    cufon = false;
    cufon = true;
    

    if (cufon)
    {
        //Cufon.replace("h1,h2",{position: 'relative'});
        Cufon.replace("h1",{
            position: 'relative'
        });

        //Cufon.replace(".image_thumb h1,.image_thumb h2,.image_thumb h3",{position: 'relative'});
        //h3 
        Cufon.replace(".image_thumb h1,.image_thumb h2",{
            position: 'relative'
        });

        Cufon.replace("#left a.forStudents,#left a.forAll,#left a.forParents",{
            position: 'relative'
        });
    }
}

//jQuery.datepicker.debug =  true;

jQuery.datepicker.setDefaults($.datepicker.regional['cs']);

jQuery.datepicker.oldUpdateDatepicker = jQuery.datepicker._updateDatepicker;

jQuery.datepicker._setHoovers = function ()
{
    // Access the API of a previously initatied simpletip var api = $('JQUERY SELECTOR').eq(0).simpletip();
    // Perform a simple API call to update tooltip contents api.update('New tooltip content!');

    jQuery('#datepicker td.Action').qtip(
    {
        //tip: true
        start : true

        ,
        prerender : true

        ,
        content: {
        //text: 'I really like owls!',
        //title: { text: 'Program:' }
        }
        ,
        hide: {
            fixed: true // Make it fixed so it can be hovered over !!
            ,
            delay: 200
        //,effect: 'slide'
        }
        ,
        show: {
            //effect: 'slide'
            solo: true
        }

        ,
        position: {
            corner: {
                //target: 'topRight',
                //tooltip: 'bottomLeft'
                target: 'rightMiddle',
                tooltip: 'leftMiddle'
            }
        }

        ,
        style: {
            width:
            {
                min: 75
                ,
                max: 1000
            }
        }

    }

    );

}

jQuery.datepicker._loadCalendarData = function(month,year,inst)
{
    console.log('instance datepickeru');
    console.debug(inst);

    //var datePicker = jQuery("#datepicker").datepicker;
    //jQuery("#datepicker .ui-datepicker-calendar").hide();
    //jQuery("#datepicker").datepicker( 'disable' ) ;

    var xmlHttpR = jQuery.getScript('/novinky/calendar/month/' + month + '/year/' + year + '/',
        function (jsonData, textStatus) {

            console.log('global data Program changed:');
            console.debug(Program);
            //console.debug(jsonData);
            //console.debug(jsonData);

            //ProgramGlobal = jsonData;
            ProgramGlobal = Program;

            //inst._notifyChange($.datepicker._curInst);

            //zavolat datepicker update udalost
            console.log('updating calendar:');

            //glob_datepicker._updateDatepicker();
            //if (typeof glob_datedatePickerpicker != 'undefined')
            {
                console.log('INST updating calendar:');
                jQuery.datepicker._updateDatepicker(inst);
            }

            jQuery("#datepicker").datepicker( 'enable' ) ;
            jQuery("#datepicker .ui-datepicker-calendar").show();

        }

        );

}

jQuery.datepicker._updateDatepicker = function(inst)
{
    this.oldUpdateDatepicker(inst);
    //to ensure that the old code still runs
    console.log('new _updateDatepicker');
    this._setHoovers();
////this ensures that the onChangeMonthYear event is fired correctly }
}


function init()
{
    //access iframe
    /*
        $(document).ready(function(){
        $('#frameID').load(function(){
            $('#frameID').contents().find('body').html('Hey, i`ve changed content of <body>! Yay!!!');
        });
    });*/



    $("form#loginForm").submit(function() {
        //ajax login
        //$.ajax(options)

        console.log("login test");

        //var path = "/vosmoa/index.php?pgID=login&XDEBUG_SESSION_START=netbeans-xdebug";
        var path = "/vosmoa/index.php?pgID=login";
        $.post(path, $("form#loginForm").serialize(),
            function(data){

                console.log("login done");
                console.log(data);
            
                //$("iframe#iframeContent").attr("src","/vosmoa/index.php");

                if (data == "prihlasen")
                    //location.href = "/iframe/rozvrh";
                    location.href = "/iframe/afterLogin/";
                else
                    $("<div/>").attr("title","Přihlášení").html("Zadané heslo nebo jméno není správné").dialog(
                    {
                        draggable: true,
                        modal: true,

                        buttons: [
                        {
                            text: "Ok",
                            click: function() {
                                $(this).dialog("close");
                            }
                        }
                        ]
                    }
                    );

            });

        //refresh iframe content

        return false;

    });

    //logout
    $("#loginpass #logout").click(function() {
        //ajax login
        //$.ajax(options)

        console.log("logout test");

        $.get("/vosmoa/index.php?pgID=logout", null,
            function(data){

                console.log("logout done");
                console.log(data);

                //$("iframe#iframeContent").attr("src","/vosmoa/index.php");

                //if (data == "prihlasen")
                location.href = "/iframe/rozvrh";

            });

        //refresh iframe content

        return false;

    });

    /*
     $("#loginpass #lostPass").click(function() {
        //ajax login
        //$.ajax(options)

        console.log("lost pass");

        $.get("/vosmoa/index.php?pgID=lostpsw",null,
        function(data){
            $(data).find("#obsah").dialog()
        });

        return false;

    });
    */
   
    jQuery('iframe#iframeContent').iframeAutoHeight({
        heightOffset: 0
    });


    $(".notAuthorized").click(
        function () {

            $("<div/>").attr("title","Není přístup").html("Nejste přihlášen...").dialog(
            {
                draggable: true,
                modal: true,

                buttons: [
                {
                    text: "Ok",
                    click: function() {
                        $(this).dialog("close");
                    }
                }
                ]
            }
            );

            return false;
        }


        );



    $("#datepicker").datepicker(
    {
        inline: true,
        dateFormat: 'dd.mm.yy',
        showButtonPanel:false,
        changeMonth: true,
        //changeYear: true,
        appendText: '(yyyy-mm-dd)',

        onChangeMonthYear: function(year, month, inst)
        {
            //alert('menim year month.')

            console.log('menim mesic rok nacist aktualni data');

            //console.debug(jQuery(".Action a"));

            jQuery.datepicker._loadCalendarData(month,year,inst);

        //setHooverTips();

        }
        ,
        onSelect: function(dateText, datePick)
        {
            console.log("select");
            console.debug(datePick);
            console.debug(dateText);
            console.log("select end");

        //console.log(datePick.selectedDay);

        },

        beforeShowDay: function(date)
        {
            //ziskat globalni promenou a projit zda je den v seznamu udalosti


            var datum = new Date();

            var poleAkci = new Array();
            var dayInfo = new Array();

            //prijede z PHP

            //akce test
            /*
            poleAkci[1] = new Array();
            poleAkci[2] = 'Super akce pravidelne 2 den v mesici.';

            poleAkci[10] = 'Super akce pravidelne 10 den v mesici.';
            */

            poleAkci = Program;

            //console.log(date.getDate());

            var denVmesici = date.getDate();
            //ano

            //akce vsechny
            if (poleAkci[denVmesici] != undefined)
            {

                console.log ('Akce je: ' + denVmesici );
                console.log ('v poli: ' + poleAkci[denVmesici] );
                console.log (poleAkci[denVmesici]);

                dayInfo[0] = true;

                //class name
                dayInfo[1] = 'Action';

                //zobrazen
                dayInfo[2] = "";
                //najit vsechny akce pro dany den

                //console.debug(poleAkci[denVmesici]);

                AkceDen = poleAkci[denVmesici];

                var akce;

                //vice akci v jednom dnu
                for (var i = 0; i < poleAkci[denVmesici].length; i++)
                {
                    //console.log('jedu pres akce');

                    akce = poleAkci[denVmesici][i];

                    //console.debug(poleAkci[denVmesici][i]);

                    /*dayInfo[2] += poleAkci[denVmesici][i]["nadpis"];*/

                    dayInfo[2] += ' <a href=\''+ akce["url"] + '\'> ' + akce["nadpis"] + '</a>';

                    if (poleAkci[denVmesici].length-1 != i)
                    {
                        dayInfo[2] += ', ';

                    }
                }

            }
            else
            {
                dayInfo[0] = false;

                //class name
                dayInfo[1] = 'noAction';
                //zobrazen
                dayInfo[2] = '';
            }

            //nelze nastavit hovery protoze se generuji pozdeji nez je nyni nastavime

            return dayInfo;
        }
    });


    cufonGo()

    //$('.clearField').clearField();


    //
    //
    //Cufon.replace('h1')('h2');
    //Cufon.replace('#content > h1:first-child')

    /*
    Cufon.replace('h1', { fontFamily: 'Frutiger LT Std' });
    Cufon.replace('h2', { fontFamily: 'Myriad Pro' });
    */

    /********* METADATA *******/
    //$.metadata.setType('attr','data');

    /*
    jQuery.prompt.setDefaults({
        //prefix: 'myPrompt',
        show: 'slideDown'
    });
*/

    //    $(document).pngFix();

    //PDF ikony

    // Add pdf icons to pdf links
    $("a[href*='.pdf']").addClass("pdf");

    $("a[href*='.doc']").addClass("doc");
    $("a[href*='.DOC']").addClass("doc");

    $("a[href*='.xls']").addClass("xls");

    // Add txt icons to document links (doc, rtf, txt)
    $("a[href*='.txt'], a[href*='.rtf']").addClass("txt");

    //case insensitive
    /*
    $('your-selector').filter(function() {
        return /some value/i.test(this.href);
    });
     */


    // Add zip icons to Zip file links (zip, rar)
    //$("a[href$='.zip'], a[href$='.rar']").addClass("zip");

    // Add email icons to email links
    //$("a[href^='mailto:']").addClass("email");

    //Add external link icon to external links -
    /*
    $('a').filter(function() {
        //Compare the anchor tag's host name with location's host name
        return this.hostname && this.hostname !== location.hostname;
    }).addClass("external");
    */


    function mycallbackform(v,m,f){
        if(v == true)
        {
            //  $.prompt(v +' ' + f.password);
            $.get('/reality/passCheck/heslo/' + f.password + '/id/' + f.id_reality + '/',
                function(html)
                {

                    var i = 0;

                    if (html == 'true')
                    {
                        //alert('heslo ok, id_reality:' + f.id_reality);

                        $.prompt("Přihlášení se podařilo, v detailu své reality naleznete nové volby.");

                        document.location = f.url;
                    }
                    else
                        //alert('spatne heslo');
                        $.prompt("Přihlášení se nepodařilo. Špatné heslo.");
                });
        }
    }

    $("#clientLogin").click(function()
    {
        var url = $(this).data('url');
        var data = $(this).metadata('id_reality');

        console.log(data);
        //var url = $(this).data('return_url');

        var txt = 'Vložte Vaše heslo: <input type="text" id="password" name="password" value=""/> <input type="hidden" id="id_reality" name="id_reality" value="' + data.id_reality + '"/> <input type="hidden" id="url" name="url" value="' + data.url + '"/> ';

        $.prompt(txt,{
            submit: mycallbackform,
            buttons: {
                Odeslat: true,
                Zrušit: false
            }
          
        }
        );
    });

    /*
    $(function() {
        $('.truncate').truncate(
        {
            max_length: 400,
            more: '...více',
            less: 'méně'
        });
    });
*/

    // *************** combo
    //$(".qfelement select").sexyCombo();



    // ******** http://gmap.nurtext.de/documentation.html

    /*
   $("#map_canvas").gMap({ markers: [{ latitude: 47.651968,
                              longitude: 9.478485,
                              html: "_latlng" },
                            { address: "Tettnang, Germany",
                              html: "The place I live" },
                            { address: "Langenargen, Germany",
                              html: "_address" }],
                  address: "Braitenrain, Germany",
                  zoom: 10 });
     */


    $('#right .MyPortalRealityPolozka').hover(
        function()
        {
            $(this).addClass('hover');

            $(this).find(".MyPortalRealityStav").slideToggle();
        }
        //hover out
        ,
        function()
        {
            $(this).removeClass('hover');

            $(this).find(".MyPortalRealityStav").slideToggle();
        }
        );

 
    /*****************   HIGHTLITE    *******************/
    //vlevo
    //
    //$("form#mainform").highlight();

    //$('form#mainform input').highlight();

    //$("table").highlight();

 
    // -------------- oprava vyrendrovaneho stromu kde jsou prazdne li
    //najdeme je a vymazeme
    $(".leftmenu ul li").each(
        function (i)
        {
            if ( $.trim($(this).text()) == "")
            {
                //console.log('mazu node');
                //console.log($(this));

                $(this).remove();
            }
            else
            {

     
        }
        }
        );


    /********** LIGHTBOX EFECT **************/

    //$('a.thickbox').lightBox();


    $("a.thickbox").fancybox();

    //$('a.thickbox').fancyZoom({scaleImg: true, closeOnClick: true});

    /*
    $("a.thickbox").colorbox(
    {
        transition:"elastic",
        //width:"75%",
        //height:"75%",
        opacity: 0.85,
        // maxWidth : true,
        // maxHeight: true,
        // scalePhotos : true,
        // slideshow : true,
        current: '{current} z {total}',
        previous : 'Předchozí',
        next : 'Další',
        close : 'Zavřít',
        slideshowStart : 'Přehrávání start',
        slideshowStop : 'Přehrávání stop'
    }

    );
*/

    /***** HOOVER CLASSES FOR BACKGROUNDS CHANGE *****/

    $('.addHover').hover(
        function()
        {
            $(this).addClass('hover');
        //console.log('hoveruji nad: ' +  $(this).attr('class'));
        }
        //hover out
        ,
        function()
        {
            $(this).removeClass('hover');
        }
        );




    /********** ZOOM IMAGE EFECT V GALERII**************/


    //build menu with DIV ID="myslidemenu" on page:
    //droplinemenu.buildmenu("mydroplinemenu")

    //login PANEL
    $(".signin").click(function(e) {
        e.preventDefault();
        $("fieldset#signin_menu").toggle();
        $(".signin").toggleClass("menu-open");
    });

    $("fieldset#signin_menu").mouseup(function() {
        return false
    });

    $(document).mouseup(function(e) {
        if($(e.target).parent("a.signin").length==0) {
            $(".signin").removeClass("menu-open");
            $("fieldset#signin_menu").hide();
        }
    });

  



    //normal menu slide

    var rev = 0

    //$("#nav:first li").hover(

    $("#menu ul:first").attr("id","nav")

    $("#nav li").hover(

        function(){
            ShowIt(this);
        },
        function(){
            HideIt(this);
        }

        )

 
}

$(document).ready(function()
{
    init();
  
}
);
