$(document).ready(function() {
    showAds();
    init_maps();
    init_gallery_fns();
    init_tiny_mce();
    init_autocomplete();
    init_topheader();
    init_market_filter();
    init_cycles();
    $("#profile_anchor").click(function() {
        var menu = $("ul#profile_links");
        if (menu.is(":visible")) menu.slideUp(200);
        else menu.slideDown(200);
    });
    $('.collapse-more a').click(function() {
        var item = $('.collapse_box');
        if (item.hasClass('collapsed')) {
            item.removeClass('collapsed').animate({
                "opacity": 1
            }, 500, function() {});
            $(this).html('Show Less...');
        } else {
            item.addClass('collapsed').animate();
            $(this).html('Show More...');
        }
    });
    $("#gpp_workshop_filter select").change(function() {
        $("#gpp_workshop_filter").submit();
    });
    $("#image_review_form").validate({
        meta: "validate"
    });
    $("#star_rating a").hover( // Handles the mouseover  


        function() {
            $(this).prevAll().andSelf().addClass('over');
            $(this).nextAll().removeClass('vote');
        }, // Handles the mouseout  


        function() {
            $(this).prevAll().andSelf().removeClass('over');
            get_votes();
        });
    get_votes(); // This actually records the vote
    $('#star_rating a').bind('click', function() {
        var star = this;
        var widget = $(this).parent();
        var clicked_data = {
            photo_id: $("#photo_id").val(),
            clicked_on: $(star).attr('class')
        };
        $.post($("#base_url").val() + 'photos/rate', clicked_data, function(INFO) {
            $(widget).data('fsr', INFO);
            set_votes(widget);
            alert("Your vote has been recorded successfully");
        }, 'json');
    });
    $('.newtarget').click(function() {
        $(this).attr("target", "_blank");
    });
    $("#slider #pager,.superscript").css({
        opacity: 0.5
    });
    $("#slider #pager, .superscript").hover( // Handles the mouseover  


        function() {
            $(this).css({
                opacity: 1
            });
        }, // Handles the mouseout  


        function() {
            $(this).css({
                opacity: 0.5
            });
        });
    $('#check_outform').click(function(e) {
        alert('You will now be directed to <em>2checkout - a secure, third party payment site</em> - to complete your purchase. Please note that this transaction will noted as payment to <strong>\"2CHECKOUT"</strong> or <strong>"2CO"</strong> on your statement, and not <strong>Gulf Photo Plus</strong>. Continue?');
        e.preventDefault();
        $.confirm({
            'title': 'Delete Confirmation',
            'message': 'You will now be directed to <em>2checkout - a secure, third party payment site</em> - to complete your purchase. Please note that this transaction will noted as payment to <strong>"2CHECKOUT"</strong> or <strong>"2CO"</strong> on your statement, and not <strong>Gulf Photo Plus</strong>. Continue?',
            'buttons': {
                'Agree': {
                    'action': function() {
                        $('#checkoutform').parent('form').submit();
                    }
                },
                'Disagree': {
                    'action': function() {
                        return false;
                    } // Nothing to do in this case. You can as well omit the action property.
                }
            }
        });
    });
    $("#event_reg").click(function() { ///validateEmail($('#email').val());
        if ($('#mobile').val() == '' || $('#email').val() == '' || $('#name').val() == '') {
            alert("Please fill the details");
            return false;
        } else return true;
    });
    $('#gallery').adGallery({});
    $('#gallery_store').adGallery({
        width: 350,
        height: 250
    });
    $(this).pngFix();
    $('ul.sf-menu').superfish({
        animation: {
            height: 'show'
        },
        // slide-down effect without fade-in 
        delay: 500,
        speed: 'fast'
    }); //    $('.gallery-thumbs li a[title]').tooltip({ position: "top center", opacity: 0.7});
    $('.thumb-slider .thumbs').jCarouselLite({
        btnNext: ".thumb-slider .r_arrow",
        btnPrev: ".thumb-slider .l_arrow",
        visible: 5,
        mouseWheel: true,
        speed: 500,
        start: get_thumb_start_pos()
    });
    $('.gallery-thumbs li a[title], .thumbs li a[title], #photo-thumb-list li a[title]').tooltip({
        position: "top center",
        opacity: 0.9,
        offset: [-3, 0]
    });
    $("#photo_search").bind({
        focus: function() {
            val = $(this).val();
            if (val == 'Search photos') $(this).val('');
            else $(this).val(val);
        },
        blur: function() {
            val = $(this).val();
            if (val == '') $(this).val('Search photos');
            else $(this).val(val);
        }
    });
    $("#site_search").bind({
        focus: function() {
            val = $(this).val();
            if (val == 'Search') $(this).val('');
            else $(this).val(val);
        },
        blur: function() {
            val = $(this).val();
            if (val == '') $(this).val('Search');
            else $(this).val(val);
        }
    });
	
    $("#username_top").bind({
        focus: function() {
            val = $(this).val();
            if (val == 'Username/Email') $(this).val('');
            else $(this).val(val);
        },
        blur: function() {
            val = $(this).val();
            if (val == '') $(this).val('Username/Email');
            else $(this).val(val);
        }
    });
    $("#password_top").bind({
        focus: function() {
            val = $(this).val();
            if (val == 'Password') $(this).val('');
            else $(this).val(val);
        },
        blur: function() {
            val = $(this).val();
            if (val == '') $(this).val('Password');
            else $(this).val(val);
        }
    });
    $("#photo_search_submit").click(function(e) {
        search_tag = $("#photo_search").val();
        if (search_tag == '' || search_tag == 'Search photos') {
            alert("Please enter a keyword to search");
            $("#photo_search").focus();
            return false;
        } else {
            $(this).parent('form').submit();
        }
    });
    init_buy_photofriday();
    $("#top_login_submit").click(function(e) {
        if ($("#username_top").val() == '' || $("#username_top").val() == 'Username/Email') {
            alert("Please enter Username/Email");
            $("#username_top").focus();
            return false;
        }
        if ($("#password_top").val() == '' || $("#password_top").val() == 'Password') {
            alert("Please enter Password");
            $("#password_top").focus();
            return false;
        }
        if ($("#username_top").val() == '' && $("#password_top").val() == '') return false;
        else {
            $("#ret_url").val($(location).attr('href'));
            $(this).parent('form').submit();
        }
    });
    $("#top_logout_link").click(function(e) {
        $.post($(this).attr('href'), {
            logout: true,
            ret_url: $(location).attr('href')
        }, function(data) {
            window.location.reload();
        }); //        window.location.reload();
        return false; //e.preventDefault();
    });
    $('.fancybox').fancybox({
        centerOnScroll: true
    });
    $(".vimeo_video").click(function() {
        $.fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'title': false,
            'width': 500,
            'height': 365,
            'href': this.href.replace(new RegExp("([0-9])", "i"), 'moogaloop.swf?title=0&amp;byline=0&amp;portrait=0&amp;color=ff0066&clip_id=$1'),
            'type': 'swf'
        });
        return false;
    }); //    $("").bind('change',function(){
    //          //window.location = $(this).val();
    //          alert($(this).val());
    //    })
    // admin checkout   
    $("input[name$='user']").change(function() {
        var test = $(this).val();
        $('.hidethis').slideUp(500).hide();
        $("#user_" + test).slideDown(500);
    });
    $(".fancy_modal").fancybox({
        'titlePosition': 'inside',
        'transitionIn': 'none',
        'transitionOut': 'none'
    });
    $("input[name$='user']").each(function() {
        var test = $(this).val();
        if ($(this).attr('checked')) $("#user_" + test).show();
    });
    init_validation();
});

function set_votes(widget) {
    var avg = $(widget).data('fsr').avg_rate; //    window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').avg_rate);
    $(widget).find('.star_' + avg).prevAll().andSelf().addClass('vote');
    $(widget).find('.star_' + avg).nextAll().removeClass('vote');
}
function get_votes() {
    $('#star_rating').each(function() {
        var widget = this;
        var out_data = {
            fetch: 1,
            photo_id: $("#photo_id").val()
        };
        $.post($("#base_url").val() + 'photos/rate', out_data, function(INFO) {
            $(widget).data('fsr', INFO);
            set_votes(widget);
        }, 'json');
    });
}
function showAds() {
    $.ajax({
        type: "POST",
        url: $("#base_url").val() + 'ad/get',
        data: "post=1",
        success: function(data) {
            if (data != '') $('.ad.grid300').html(data);
            else {
                $('.ad.grid300').html($('#adsense').html());
            }
        }
    });
}
function get_thumb_start_pos() {
    for (i = 0; i < $("#thumb_count").val(); i++) {
        if ($('.thumb-slider .thumbs img#' + i).attr('itemref') == $("#photo_id").val()) {
            $('.thumb-slider .thumbs img#' + i).parent('li').css('border-color', '#98E5E4');
            return i;
        }
    }
    return 0;
}
function init_maps() {
    $("#map").gMap({
        markers: [{
            latitude: 25.141837,
            longitude: 55.225638,
            html: '<div class="map_info">\n\
                    <p class="maphead">    Gulf Photo Plus</p>\n\
                    <p>    Street 8, Al Serkal Ave, Al Qouz.</p>\n\
                    <p>    Phone: +971 4 380 8545 </p>\n\
                    </div>',
            popup: true
        }],
        zoom: 15,
        controls: ["GSmallMapControl"],
        maptype: G_NORMAL_MAP,
        scrollwheel: false
    });
    $("#wloc_map").gMap({
        markers: [{
            latitude: $("#w_latitude").val(),
            longitude: $("#w_longitude").val(),
            html: '<div class="map_info"><p style="margin:6px 4px;">  ' + $("#wl_title").html() + ',<br/>' + $("#w_short_info").val() + '</p></div>',
            popup: true
        }],
        zoom: 15,
        controls: ["GSmallMapControl"],
        maptype: G_NORMAL_MAP,
        scrollwheel: false
    });
}
function init_gallery_fns() {
    $("#gallery_pick #set_gpp_pick").click(function() {
        id = $("#photo_id").val();
        alert("Set ?" + id);
        $.ajax({
            type: "POST",
            url: $("#base_url").val() + 'photos/set-gpp-pick',
            data: "id=" + id + "&a=1",
            success: function(data) { // Logic to output dynamic content.
                if (data == '1') $('#gallery_pick').html("<span>GPP Pick</span>");
            }
        });
    });
}
function init_tiny_mce() {
    $('textarea.tinymce').tinymce({ // Location of TinyMCE script
        script_url: $("#base_url").val() + 'js/tiny_mce/tiny_mce.js',
        // General options
        theme: "advanced",
        skin: "cirkuit",
        // Theme options
        theme_advanced_buttons1: "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,pastetext,bullist,numlist,undo,redo",
        theme_advanced_buttons2: "",
        theme_advanced_buttons3: "",
        theme_advanced_buttons4: "",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "center",
        theme_advanced_statusbar_location: false,
        theme_advanced_resizing: false,
        // Example content CSS (should be your site CSS)
        content_css: $("#base_url").val() + "css/styles.css" //        // Drop lists for link/image/media/template dialogs
    //        template_external_list_url : "lists/template_list.js",
    //        external_link_list_url : "lists/link_list.js",
    //        external_image_list_url : "lists/image_list.js",
    //        media_external_list_url : "lists/media_list.js",
    });
}
function init_autocomplete() {
    $("#username_checkout,.username_autocomplete").autocomplete($("#base_url").val() + "get_user_names", {
        width: 210,
        selectFirst: false
    });
}
function init_validation() {
    var container = $('div.errors');
    jQuery.validator.addMethod("noSpace", function(value, element) {
        return value.indexOf(" ") < 0 && value != "";
    }, "No space please and don't leave it empty");
    $("#register_form,#checkout_form,#image_review_form").validate({
        rules: {
            user: {
                noSpace: true
            }
        },
        errorContainer: container,
        errorLabelContainer: $("ol", container),
        wrapper: 'li',
        meta: "validate"
    });
}
function init_topheader() {}
function init_market_filter() {
    $("#market_type, #market_category").bind('change', function() {
        window.location = $(this).val();
    });
}
function init_cycles() {
    $('.cycleButton').cycle({
        fx: 'scrollHorz',
        delay: 5000
    });
    $('#fotoweekend_slider, .home_ad').cycle({
        fx: 'fade',
        delay: 5000
    });
    $('#slider .slides').cycle({
        fx: 'fade' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
    });
    $('.fuji_leader').cycle({
        fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        timeout:3000
    });
    $('.fuji_ad').cycle({
        fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
        timeoutFn:function (currElement, nextElement, opts, isForward) { 
            // here we set even number slides to have a 2 second timeout; 
            // by returning false for odd number slides we let those slides 
            // inherit the default timeout value (4 sec) 
            var index = opts.currSlide; 
            return index == 2 ? 5000 : 2000; 
        } 
        
    });
}
function validateEmail(elementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
}
function init_buy_photofriday() {
    $('.photofriday_grid').find('.sub_total span').html(0);
    $('.photofriday_grid').each(function() {
        if ($(this).find('input[type="radio"]:checked')) {
            item = $(this).find('input[type="radio"]').is(':checked');
            $(item).parents('.slot').addClass('selected');
        }
    });
    init_photofriday_form_animations();
    $("#buy_photofriday_submit").click(function() {
        pf_count = 0;
        $('.photofriday_grid').each(function() {
            if ($(this).find('input[type="radio"]').is(':checked')) {
                pf_count++;
                $("#buy_photofriday_submit").parents('form').submit();
                return true;
            }
        });
        if (pf_count == 0) alert("Please select some workshops!");
        return false;
    });
    $("#add_pf_ticket").click(function() {
        ticket_cnt = $("#no_pf_ticket").val();
        var newticket = $("#photofriday_buy_form .photofriday_grid:first").clone();
        newticket.find('input[type="radio"]').each(function() {
            temp = $(this).attr('name');
            temp = temp.replace('ticket_0', 'ticket_' + ticket_cnt);
            $(this).attr('name', temp);
            temp = $(this).attr('id');
            temp = temp.replace('session_0', 'session_' + ticket_cnt);
            $(this).attr('id', temp);
        });
        newticket.find('label').each(function() {
            temp = $(this).attr('for');
            temp = temp.replace('session_0', 'session_' + ticket_cnt);
            $(this).attr('for', temp);
        });
        $("#no_pf_ticket").val(parseInt(ticket_cnt) + 1);
        newticket.find('input[type="radio"]').prop("checked", false);
        newticket.find('.slot').removeClass('selected');
        newticket.find('.sub_total span').html(0);
        newticket.find('.head h4').html("Choose Classes for ticket " + $("#no_pf_ticket").val());
        newticket.appendTo('#photofriday_buy_form');
        init_photofriday_form_animations();
    });
    $("#delete_pf_ticket").click(function() {
        ticket_cnt = $("#no_pf_ticket").val();
        if (ticket_cnt > 1) {
            $("#photofriday_buy_form .photofriday_grid:last").remove();
            $("#no_pf_ticket").val(parseInt(ticket_cnt) - 1);
            init_photofriday_form_animations();
        } else {
            alert("At least one ticket must be selected!");
            return false;
        };
    });
}
function init_photofriday_form_animations() {
    if (parseInt($("#no_pf_ticket").val()) > 1) $("#delete_pf_ticket").show();
    else $("#delete_pf_ticket").hide();
    if (parseInt($("#no_pf_ticket").val()) > 10) $("#add_pf_ticket").hide();
    else $("#add_pf_ticket").show();
    $('.fancybox').fancybox({
        centerOnScroll: true
    });
    $('.photofriday_grid a.button').click(function() {
        $(this).parents('.photofriday_grid').find('input[type="radio"]').prop("checked", false).effect("pulsate", {
            times: 3
        }, 50);
        $(this).parents('.photofriday_grid').find('.slot').removeClass('selected');
        $(this).parents('.photofriday_grid').find('.sub_total span').html(0);
        $(this).parents('.photofriday_grid').find('.sub_total').effect("shake", {
            times: 3,
            distance: 2
        }, 30);
    });
    $('.photofriday_grid input[type="radio"]').bind('click', function() {
        if ($(this).is(':checked')) { //alert($(this).val());
            amount = $(this).parents('.photofriday_grid').find('input[type="radio"]:checked').length;
            if (amount > 3) amount = 3;
            total = amount * 14;
            $(this).parents('.session').find('.slot').removeClass('selected');
            $(this).parents('.slot').addClass('selected');
            $(this).parents('.photofriday_grid').find('.sub_total span').html(total);
            $(this).parents('.photofriday_grid').find('.sub_total').effect("shake", {
                times: 3,
                distance: 2
            }, 30);
        }
    });
}

