$(document).ready(function() {
    // Facebook Connect
    fbConnectButton(gettext("Connect with Facebook"));

    // show city chooser
    $('#city-change-link').click(function(){
        $(this).hide();
        $('#city-list').show();
    });

    // redirect to selected city
    $('#city-list').change(function(){
        window.location = "/cities/" + $(this).val() + "/"
    });

    // wrap ribbon around content
    $('div.ribbon').after('<div class="ribbon-bottom"></div>');
    $('.dark-ribbon').after('<div class="dark-ribbon-bottom"></div>');

    // display any link that has a class name fancybox in a fancybox
    $("a.fancybox").fancybox();

    // if there are any errors in promocode, re-open fancybox
    if($("#bdvoucher-deal-checkout-promocodeform ul.errorlist").length>0){
        $("a.fancybox").trigger('click');
    }

    // *! if page is not email refusal page
    // prompt daily deal subscription form
    if(window.location.pathname.indexOf('/refuse/') == -1){
        prompt_daily_deal_subscription();
    }

    // validate and post subscription form on index page
    $("#subscription_form").validate({
        submitHandler: function(form) {
            jQuery(form).ajaxSubmit({
                url: $("#subscription_form").attr("action") + '?ajax=true',
                success: function() {
                    $("#thankyou").show();
                    $("#signup").slideUp();
                }
            });
        },
        errorElement: "span",
        errorLabelContainer: $("#email_errors")
    });

    // validate and post subscription form on deal page sidebar
    $("#quick_subscription_form").validate({
        submitHandler: function(form) {
            jQuery(form).ajaxSubmit({
                url: $("#quick_subscription_form").attr("action") + '?ajax=true',
                success: function() {
                    $("#thankyou").show();
                    $("#quick_subscription_form").hide();
                }
            });
        },
        errorElement: "span",
        errorLabelContainer: $("#email_errors")
    });

    if(LANGUAGE_CODE.search("tr") == 0){fix_turkish_capitalizations()}

    // initialize any select all/none buttons on current pages
    $("#select_all").click(function(event){
        event.preventDefault();
        $("input:checkbox").attr("checked","checked");
    });
    $("#select_none").click(function(event){
        event.preventDefault();
        $("input:checkbox").removeAttr('checked');
    });

    shopping_cart();

    $('.clickable').click(function (e) {
        e.preventDefault();
        var link = $(this).attr('data-url');
        window.location = link;
    });

    // personalize invitation link
    $("#change-username-link").click(function(){
        $("#change-username-form").show();
        $("#invitation-link-container").hide();
    });
    $("#cancel-button").click(function(){
        $("#invitation-link-container").show();
        $("#change-username-form").hide();

    });

    var msg = "";
    var options = {
           //target: ".response",
           success: function(responseText, statusText, xhr) {
               if(responseText=="ALREADY_CLAIMED"){
                  alert(gettext("You can change your username only once."));
               } else if(responseText=="ALREADY_TAKEN"){
                 alert(gettext("This username is already taken, please try another username."));
               } else if(responseText=="SYNTAX_ERROR"){
                  alert(gettext("Username can only contain numbers, letters, underscore and dash, between 3 and 30 characters."));
               } else if(responseText=="INVALID_REQUEST"){
                  alert(gettext("You're not allowed to reach this page"));
               } else {
                   alert(gettext("Your username has been changed to ") + responseText);
                   window.location.reload();
               }
            },
        };
    $('#change-username-form').ajaxForm(options);

    // Lazy load the images
    $("img.lazy").show().lazyload({ threshold : 500,
                                    effect : "fadeIn"});
});

function fbConnectButton(text){
    // If button text not specified, use "Connect" as default text
    if(text){ fbCaption = text; }
    else{ fbCaption = "Connect" }

    var login_elem = $("<form></form>")
                        .attr("id", "fb-login")
                        .attr("method", "post")
                        .attr("action", FACEBOOK_LOGIN_URL)
                        .append($(SOCIAL_CSRF_TOKEN))
                        .appendTo($("div#fb-connect-button"));
    var postLogin = function() {
        $("form#fb-login").submit();
    };

    var handler = function() {
        login_elem.append($.facebook_login_button({
            caption: gettext(fbCaption),
            size: "small",
            callback: postLogin
        }));
    };

    if (!window.FB) {
        $(document).bind("FACEBOOK_INIT", handler);
    } else {
        handler();
    }
}

function shopping_cart(){
    var cart_form = $('#bdvoucher-deal-purchase-cart-form');

    // This handles the quantity update link
    $('a.update-total', cart_form).click(function(e){
        e.preventDefault();
        var qty = $(this).siblings('input').val();
        if(qty == "0"){
            var confirmation = confirm(gettext("Are you sure you want to delete this item?"))
            if (confirmation){
                cart_form.submit();
            }
            else{
                window.location.reload();
            }
        }
        else{
            cart_form.submit();
        }
    });

    // This handles the delete checkbox
    $('input[type=checkbox]', cart_form).click(function(e){
        // show delete confirmation message only if the checkbox is checked after click
        if($(this).attr('checked')){
            var confirmation = confirm(gettext("Are you sure you want to delete this item?"))
            if (confirmation){
                cart_form.submit();
            }
            else{
                $(this).attr('checked', false);
            }
        }
    });
}

function fix_turkish_capitalizations() {
    // Two different methods to replace the text is needed
    $('span, p, a, div, h1, h2, h3').each(function() {
        if($(this).css('text-transform')=="uppercase") {
            $(this).html($(this).html().replace(/i/g,"İ"));
            $(this).html($(this).html().replace(/ı/g,"I"));
        }
    });

    $('input').each(function() {
        if($(this).css('text-transform')=="uppercase") {
            $(this).val($(this).val().replace(/i/g,"İ"));
            $(this).val($(this).val().replace(/ı/g,"I"));
        }
    });
}

// email collection function
function prompt_daily_deal_subscription(){

    // define parameters
    var cookieDuration = 7;
    /*
        Either an integer specifying the expiration date from now on in days or a Date object.
        If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
        If set to null or omitted, the cookie will be a session cookie and will not be retained
        when the the browser exits
    */

    var timeoutDuration = 3000; // waiting time to automatically close the email collection box on successful collection

    // if there is NO cookie and user is NOT logged in
    if (!$.cookie("email-collection") && IS_AUTHENTICATED == false) {
        // create email collection box
        $("a#email-box-link").fancybox({
            padding:'0',
            overlayColor: '#333',
            modal: true,
            onComplete: function(){
                if($.cookie("dynasta_email_address"))
                {
                    $("#email-collection-input-field-container input[type=text]").val($.cookie("dynasta_email_address").replace(/"/g, ""));
                }

                // display, validate and post subscription form
                $("#email-collection-form").validate({
                    submitHandler: function(form) {
                        jQuery(form).ajaxSubmit({
                            url: $("#email-collection-form").attr("action") + '?ajax=true',
                            success: function() {
                                $("#email-collection-form").hide();
                                $("#email-box-success").show();
                                createCookie(999);
                                timeoutID = window.setTimeout("$.fancybox.close();", timeoutDuration);
                            }
                        });
                    },
                errorElement: "span",
                errorLabelContainer: "#email-collection-errors"
                });


                // close fancybox when any link that has a class name close-fancybox is clicked
                $("a.close-fancybox").click(function(){$.fancybox.close();});

            },
            onClosed: function(){
                // remove #email-box-scissors to prevent it from showing up in other fancybox used
                $("#email-box-scissors").remove();
            }
        });

        // automatically display email collection box
        $("a#email-box-link").trigger('click');

        // append the scissors icon
        $("#fancybox-outer").append('<div id="email-box-scissors"></div>');

        // create a cookie
        createCookie(cookieDuration);

    }
    // if NO cookie and user IS logged in
    else if (!$.cookie("email-collection") && IS_AUTHENTICATED == true) {
        // create the cookie
        createCookie(999);
    }
    // if HAS cookie AND/OR user IS logged in
    else {
        // do nothing
        return false;
    }
}

function createCookie(duration){
    $.cookie("email-collection", "done", {expires: duration, path: '/'});
}

// this function takes in argument `places` with format:
// [new google.maps.LatLng(Lattitude, Longitude)]
function google_maps_initialize(places) {
    var centerLoc = [];
    var bounds = new google.maps.LatLngBounds;
    if(places.length > 0) {
        // if only one location: zoom to location
        if(places.length == 1) {
            centerLoc.push(places[0][0]);
        }
        // if more than one location: show all locations on map
        else if(places.length > 1) {

            for(var p=0;p<places.length;p++) {
                bounds.extend(places[p][0]);
            }
            centerLoc.push(new google.maps.LatLng(bounds.getCenter().lng(), bounds.getCenter().lat()));
        }
        var myOptions = {
            zoom: 15,
            center: centerLoc[0],
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("google-maps-canvas"), myOptions);
        if(places.length > 1) {
            map.fitBounds(bounds);
        }
        for(var i=0; i < places.length; i++) {
            new google.maps.Marker({position: places[i][0], map: map, title:places[i][1]});
        }
    }
    // if no locations
    else {
        document.getElementById("google-maps-canvas").style.display="none";
    }
}

function resizeIframe(height) {
    document.getElementById('partner-frame').height = parseInt(height)+25;
}
