$(document).ready(function(){

    /* Ajax stuff for access control */
    $('a.set-access-control').click(function(){
        var thisRow = $(this).parents('tr');

        var thisRowAllowed   = thisRow.children('td.allowed');
        var thisRowLoading   = thisRow.children('td.actions').children('div.ajaxloading');
        var thisRowLinkAllow = thisRow.children('td.actions').children('div.links').children('span.allow');
        var thisRowLinkDeny  = thisRow.children('td.actions').children('div.links').children('span.deny');

        // Show the loading image
        thisRowLoading.show();

        // Hide both link, no need to check
        thisRowLinkAllow.hide();
        thisRowLinkDeny.hide();

        $.getJSON($(this).attr('href'), function(data){
            // Show back the links
            thisRowLoading.hide();

            if(data.AccessControl.success == 1){
                thisRowAllowed.text(data.AccessControl.allowedString);

                if(data.AccessControl.allowed == 1){
                    thisRowLinkDeny.show();
                    thisRow.removeClass('background-yellow');
                    thisRow.effect('highlight', 0, 2000);
                }else{
                    thisRowLinkAllow.show();
                    thisRow.addClass('background-yellow');
                }
            }else{
                alert('I cannot set the permission at the moment. Please try again.');
                if(data.AccessControl.allowed == 1){
                    thisRowLinkAllow.show();
                }else{
                    thisRowLinkDeny.show();
                }
            }
        });

        // Prevent the link follow the destination
        return false;
    });

    /* Accordion for access control */
    if($('.accordion').length){
        $('.accordion').accordion({ active: false, animated: false, autoHeight: false, collapsible: true });
    }

    /* Popup */
    $('.popup').click(function(){
        window.open($(this).attr('href'));
        return false;
    });

    /* Fix for IE hover */
    if($.browser.msie){
        /* Fix for Menu hover */
        $('.nav li').each(function(){
            $(this).mouseover(function(){
                $(this).children('ul').css('display', 'block');
            });

            $(this).mouseout(function(){
                $(this).children('ul').css('display', 'none');
            });
        });
    }

    /* News column/nanggroe */
    $('#useNanggroe').click(function(){
        if($('#useNanggroe').attr('checked')){
            $('#newsColumn').hide();
            $('#newsNanggroe').show();
        }else{
            $('#newsColumn').show();
            $('#newsNanggroe').hide();
        }
    });

    /* News photo checkbox */
    $('#useExistingPhoto').click(function(){
        if($('#useExistingPhoto').attr('checked')){
            $('#photoUpload').hide();
            $('#photoExisting').show();
        }else{
            $('#photoUpload').show();
            $('#photoExisting').hide();
        }
    });

    /* News photo checkbox */
    $('#photoExistingInput').change(function(){
        if($(this).val()){
            $('#photoExistingButton').removeAttr('disabled');
            $('#photoExistingPreview').text(' ');
        }else{
            $('#photoExistingButton').attr('disabled', 'disabled');
            $('#photoExistingPreview').text(' ');
        }
    });

    /* News photo checkbox */
    $('#photoExistingButton').click(function(){
        var photo_title = $('#photoExistingInput').val();
        if(photo_title){
            $.ajax({
                url: '/photos/preview/' + photo_title,
                success: function(data){
                    $('#photoExistingPreview').html(data);
                }
            });
        }
    });

    /* Autocomplete */
    if($('#photoExistingInput').length){
        $('#photoExistingInput').autocomplete('/photos/autocomplete');
    }
    if($('#userAutocomplete').length){
        $('#userAutocomplete').autocomplete('/users/autocomplete');
    }
    if($('#authorAutocomplete').length){
        $('#authorAutocomplete').autocomplete('/authors/autocomplete');
    }

    /* Flow player for video */
    if($('a.flowplayer-small').attr('href')){
        flowplayer("a.flowplayer-small",
            {src: "/flash/flowplayer.swf", wmode: "transparent"},
            {
                clip: {
                    url: $(this).attr('href'),
                    autoPlay: true,
                    autoBuffering: true
                },
                play: {
                    label: null,
                    replayLabel: "Play Again"
                },
                plugins: {
                    controls:{
                        autoHide: 'always',
                        all: false,
                        fullscreen: true,
                        play: true,
                        scrubber: true
                    }
                }
            }
        );
    }

    /* Flow player large */
    if($('a.flowplayer-large').attr('href')){
        flowplayer("a.flowplayer-large",
            {src: "/flash/flowplayer.swf", wmode: "transparent"},
            {
                clip: {
                    url: $(this).attr('href'),
                    autoPlay: true,
                    autoBuffering: true
                },
                play: {
                    label: null,
                    replayLabel: "Play Again"
                },
                plugins: {
                    controls:{
                        all: false,
                        fullscreen: true,
                        play: true,
                        scrubber: true
                    }
                }
            }
        );
    }

    /* Gold price stuff */
    $('.gold-price a.ajaxRequest').click(function(){
        $('.gold-price .ajax-loading').show(1);
        $.ajax({
            url: $(this).attr('href'),
            dataType: 'json',
            type: 'GET',
            success: function(data){
                $('.gold-price h4').html(data.Gold.price);
                $('.gold-price h2 span.type').html(data.Gold.type);
                $('.gold-price .ajax-loading').hide(1);
            }
        });

        return false;
    });

    /* Bubble Popup */
    $(".bubble-popup").mouseover(function() {
        $(this).children(".bubble").show();
    });

    $(".bubble-popup object").mouseover(function() {
        $(this).children(".bubble").show();
    });

    $(".bubble-popup").mouseout(function() {
        $(this).children(".bubble").hide();
    });

    /* Search Box */
    $('#searchBox').click(function(){
        if($('#search').is(':visible')){
            $('#search').slideUp();
        }else{
            $('#search').slideDown();
        }
        return false;
    });

    /* Search box first load hide */
    $('#search').hide();

     /* Dialog */
    $('#prayertimeDialog, #earthquakeDialog, #goldpriceDialog').dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false
    });

    $('#weatherDialog').dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        draggable: false,
        width: 480
    });

    /* Weather widget */
    if($('#weather').length){
        $.ajax({
            url: '/weather/get',
            dataType: 'json',
            type: 'GET',
            success: function(data){
                $('#weather .temperature').html(data.CurrentObservation.temp_c + "&deg; C");
                $('#weather .location').html(data.CurrentObservation.ObservationLocation.city);
                $('#weather .loading').hide();
            },
            error: function(){
                $('#weather .temperature').html('N/A');
                $('#weather .loading').hide();
            }
        });
    }

    $('#weather a.dialog').click(function(){
        $('#weatherDialog').dialog('open');
        return false;
    });

    $('.weather a.dialog').click(function(){
        $('#weatherDialog').dialog('open');
        return false;
    });

    /* Earthquake widget */
    if($('#earthquake').length){
        $.ajax({
            url: '/earthquake/get',
            dataType: 'json',
            type: 'GET',
            success: function(data){
                $('#earthquake .magnitude').html(data.Magnitude);
                $('#earthquake .location').html(data.WilayahShort);
                $('#earthquake .loading').hide();
            },
            error: function(){
                $('#earthquake .magnitude').html('N/A');
                $('#earthquake .loading').hide();
            }
        });
    }

    $('#earthquake a.dialog').click(function(){
        $('#earthquakeDialog').dialog('open');
        return false;
    });

    /* Earthquake widget */
    if($('#goldprice').length){
        $.ajax({
            url: '/golds/get',
            dataType: 'json',
            type: 'GET',
            success: function(data){
                $('#goldprice .price').html(data.Gold.price);
                $('#goldprice .type').html(data.Gold.type);
                $('#goldprice .loading').hide();
            },
            error: function(){
                $('#goldprice .price').html('N/A');
                $('#goldprice .type').empty();
                $('#goldprice .loading').hide();
            }
        });
    }

    $('#goldprice a.dialog').click(function(){
        $('#goldpriceDialog').dialog('open');
        return false;
    });

    $('#goldprice .bubble a').click(function(){
        var getUrl = $(this).attr('href');

        $('#goldprice .price').empty();
        $('#goldprice .type').empty();
        $('#goldprice .loading').show();

        $.ajax({
            url: getUrl,
            dataType: 'json',
            type: 'GET',
            success: function(data){
                $('#goldprice .price').html(data.Gold.price);
                $('#goldprice .type').html(data.Gold.type);
                $('#goldprice .loading').hide();
            },
            error: function(){
                $('#goldprice .price').html('N/A');
                $('#goldprice .type').empty();
                $('#goldprice .loading').hide();
            }
        });

        return false;
    });

    /* Prayer Time widget */
    if($('#prayertime').length){
        $.ajax({
            url: '/prayertime/get',
            dataType: 'json',
            type: 'GET',
            success: function(data){
                $('#prayertime .time').html(data.PrayerTime.time);
                $('#prayertime .type').html(data.PrayerTime.type);
                $('#prayertime .location').html(data.PrayerTime.city);
                $('#prayertime .loading').hide();
            },
            error: function(){
                $('#prayertime .time').html('N/A');
                $('#prayertime .type').empty();
                $('#prayertime .location').empty();
                $('#prayertime .loading').hide();
            }
        });
    }

    $('#prayertime a.dialog').click(function(){
        $('#prayertimeDialog').dialog('open');
        return false;
    });

    $('#prayertime .bubble a').click(function(){
        var getUrl = $(this).attr('href');

        $('#prayertime .time').empty();
        $('#prayertime .type').empty();
        $('#prayertime .location').empty();
        $('#prayertime .loading').show();

        $.ajax({
            url: getUrl,
            dataType: 'json',
            type: 'GET',
            success: function(data){
                $('#prayertime .time').html(data.PrayerTime.time);
                $('#prayertime .type').html(data.PrayerTime.type);
                $('#prayertime .location').html(data.PrayerTime.city);
                $('#prayertime .loading').hide();
            },
            error: function(){
                $('#prayertime .time').html('N/A');
                $('#prayertime .type').empty();
                $('#prayertime .location').empty();
                $('#prayertime .loading').hide();
            }
        });

        return false;
    });




    /* Galleriffic */
    // We only want these styles applied when javascript is enabled
    $('.photos div.navigation').css({'width' : '300px', 'float' : 'left'});
    $('.photos div.content').css('display', 'block');

    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#thumbs ul.thumbs li').opacityrollover({
        mouseOutOpacity:   onMouseOutOpacity,
        mouseOverOpacity:  1.0,
        fadeSpeed:         'fast',
        exemptionSelector: '.selected'
    });

    // Initialize Advanced Galleriffic Gallery
    if($('#thumbs').length){
        var gallery = $('#thumbs').galleriffic({
            delay:                     6000,
            numThumbs:                 30,
            preloadAhead:              1,
            enableTopPager:            false,
            enableBottomPager:         false,
            imageContainerSel:         '#slideshow',
            controlsContainerSel:      '#controls',
            captionContainerSel:       '#caption',
            loadingContainerSel:       '#loading',
            renderSSControls:          true,
            renderNavControls:         true,
            playLinkText:              'Play Slideshow',
            pauseLinkText:             'Pause Slideshow',
            prevLinkText:              '&lsaquo; Previous Photo',
            nextLinkText:              'Next Photo &rsaquo;',
            nextPageLinkText:          'Next &rsaquo;',
            prevPageLinkText:          '&lsaquo; Prev',
            enableHistory:             false,
            autoStart:                 true,
            syncTransitions:           true,
            defaultTransitionDuration: 1000,
            onSlideChange:             function(prevIndex, nextIndex) {
                // 'this' refers to the gallery, which is an extension of $('#thumbs')
                this.find('ul.thumbs').children()
                    .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                    .eq(nextIndex).fadeTo('fast', 1.0);
            },
            onPageTransitionOut:       function(callback) {
                this.fadeTo('fast', 0.0, callback);
            },
            onPageTransitionIn:        function() {
                this.fadeTo('fast', 1.0);
            }
        });
    }

    // WYSIWYG textarea
    $('textarea').wysiwyg({
        'controls': {
            bold          : { visible : true},
            italic        : { visible : true},
            strikeThrough : { visible : false},
            underline     : { visible : true},

            separator00 : { separator : true },

            justifyLeft   : { visible : false },
            justifyCenter : { visible : false },
            justifyRight  : { visible : false },
            justifyFull   : { visible : false },

            separator01 : { visible : false, separator : true },

            indent  : { visible : true },
            outdent : { visible : true },

            separator02 : { visible : true, separator : true },

            subscript   : { visible : true },
            superscript : { visible : true },

            separator03 : { visible : true, separator : true },

            undo : { visible : true },
            redo : { visible : true },

            separator04 : { visible : true, separator : true },

            insertOrderedList    : { visible : true },
            insertUnorderedList  : { visible : true },
            insertHorizontalRule : { visible : true },

            separator05 : { separator : true },

            createLink : { visible : true },
            insertImage : { visible : true },

            separator06 : { separator : true },

            h1mozilla : { visible : true && $.browser.mozilla},
            h2mozilla : { visible : true && $.browser.mozilla},
            h3mozilla : { visible : true && $.browser.mozilla},

            h1 : { visible : true && !( $.browser.mozilla )},
            h2 : { visible : true && !( $.browser.mozilla )},
            h3 : { visible : true && !( $.browser.mozilla )},

            separator07 : { visible : false, separator : true },

            cut   : { visible : false },
            copy  : { visible : false },
            paste : { visible : false },

            separator08 : { separator : false && !( $.browser.msie ) },

            increaseFontSize : { visible : false},
            decreaseFontSize : { visible : false},

            separator09 : { separator : true },

            html : { visible : false },
            removeFormat : { visible : true }
        }
    });

    $('.daemon-progress').progressbar({value: 1}).hide();

    if($('.daemon-status').length){
        setInterval(function(){
            $.ajax({
                url: '/daemons/status',
                dataType: 'json',
                type: 'GET',
                success: function(data){
                    $('.daemon-status').html(data.status);
                    if(data.nojob == 1){
                        $('.daemon-progress').hide();
                    }else{
                        $('.daemon-progress').show();
                    }

                    if(data.percentage){
                        $('.daemon-progress').progressbar('option', 'value', data.percentage);
                    }


                },
                error: function(){
                    $('.daemon-status').html('Not available at the moment');
                }
            });
        }, 5000);
    }

    /* Admin search box */
    if($('.admin-search-box').length){
        if($('.admin-search-box input#query').val() == ''){
            $('.admin-search-box').hide();
        }
    }

    $('.actions a.admin-search').click(function(){
        $('.admin-search-box').toggle();
        return false;
    });

    $('a.disabled').click(function(){
        return false;
    });

    $('a.fancybox').fancybox();

    $('div.transparent').css('opacity', '0.7');

    //$('#headline-slideshow').nivoSlider();
    $("#slideshow").css("overflow", "hidden");
    $("ul#slides").cycle({
        fx: 'fade',
        pause: 1,
        prev: '#prev',
        next: '#next'
    });
    $("#slideshow").hover(function() {
        $("#slideshow ul#nav").fadeIn();
    },
    function() {
        $("#slideshow ul#nav").fadeOut();
	});
});

