// custom js & jquery
var bitlyUrl = false;

if (typeof console === 'undefined') {
    var console={log: function () {}};
}


function generateLink( tlb_link )
{
    var BITLY_URL = 'http://api.bitly.com';
    var BITLY_SHORTEN = '/v3/shorten';
    var BITLY_API_KEY = 'R_05a89123a93ebb3f2342d4daab851242';
    var BITLY_USER = 'thelocalbest';
    var URL_ENCODED = encodeURIComponent( tlb_link );
    var link = BITLY_URL + BITLY_SHORTEN +'?login=' + BITLY_USER + '&apiKey=' + BITLY_API_KEY + '&longUrl=' + URL_ENCODED + '&format=json';
    var bitly_link = null;
    
    if ($.cookie('the_local_best_url')){
        bitly_link = $.cookie('the_local_best_url');
    } else {
        $.getJSON( link, function( bitly_result ){
            var bitly_link = bitly_result.data.url;
            $.cookie('the_local_best_url', bitly_link);
        });
    }
    
    return bitly_link;
}

function shareLink(link)
{
    if ($('#facebookImage').val()) {
        var facebookImageFile = 'http://localsloveus.com/images/' + $('#facebookImage').val();
    } else {
        var facebookImageFile = 'http://sbla.jrm.llu.blendinteractive.com/images/LLU_2C.jpg';
    }
    var twitterSummary='Just finished voting in the "Locals Love Us" contest. ' +
        ' Fun! Use my link to vote and we get entered to win prizes: ~',
    facebookSummary="Vote in the \"Locals Love Us\" contest and help your favorite places " +
        "win awards. You'll get a shot at winning some cool prizes just for " +
        "voting. Prizes like a vacation for two, iPad, Kindle, Nook, a catered " +
        "party for 30 and tons of tshirts, backpacks, local gift cards and more!",
    facebookImage= facebookImageFile,
    facebookTitle="Let your love flow",
    emailSubject="Vote in Locals Love Us",
    emailSummary="Just finished voting in the \"Locals Love Us\" contest. Fun! " +
        "Use my link to vote and we get entered to win prizes: ~",
    BITLY_URL = 'http://api.bitly.com',
    BITLY_SHORTEN = '/v3/shorten',
    BITLY_API_KEY = 'R_05a89123a93ebb3f2342d4daab851242',
    BITLY_USER = 'thelocalbest',
    URL_ENCODED = encodeURIComponent( $(link).attr('href') ),
    apiUrl = BITLY_URL + BITLY_SHORTEN +'?login=' + BITLY_USER + '&apiKey=' + BITLY_API_KEY + '&longUrl=' + URL_ENCODED + '&format=json&callback=?',
    bitly_link = null;
        
    if (!bitlyUrl) {    

        $.ajax({
            url: apiUrl,
            dataType: 'jsonp',
            cache: false,
            success: function (result) {
                bitlyUrl = result.data.url;
                $.cookie('the_local_best_url', bitlyUrl);
                shareLink(link);                    
            }
        });

        return;
    }
    
    switch ( $('img', link).attr('alt') ) {
        case 'Twitter':
            window.open(
                'http://twitter.com/home?status=' +
                    escape(twitterSummary.replace('~', bitlyUrl)),
                '_blank'
            );
        break;
        case 'Facebook':
            var facebookUrl = 
                'http://www.facebook.com/sharer.php?s=100' +
                '&p[images][0]=' + escape(facebookImage) +
                '&p[title]=' + escape(facebookTitle) +
                '&p[summary]=' + escape(facebookSummary) +
                '&p[url]=' + escape(bitlyUrl);
            window.open(facebookUrl, "_blank", 'toolbar=0,status=0,width=626,height=436');
        break;
        case 'Email':
            window.location.href = 'mailto:?subject=' + escape(emailSubject) +
                '&body=' + escape(emailSummary.replace('~',bitlyUrl));
        break;
        default:
            $('#share-link').val(bitlyUrl);
            $('.share-link').slideDown('fast');
            
    }
    
}

function updateLocation(address, latLng)
{
    var addressField = $('.location-field'),
    positionField = $('.position-field'),
    marker = null;

    positionField.val(latLng.toUrlValue());
    addressField.val(address);

    if (newmap) {
        if (newmapbounds) {
            newmapbounds.extend(latLng);
            newmap.fitBounds(newmapbounds);
        } else {
            newmap.setCenter(latLng);
        }
        marker = new google.maps.Marker({map:newmap, position:latLng, icon:'/images/your_location01.png'});
    }

}

(function ($){
    $(document).ready(function () {

        /* run gallery code */
        console.log('init');
        if($.fn.scroller) {
            console.log('gallery');
            $('.gallery').scroller({itemClass: 'gallery-line', perPage: 5, auto: false});
            $('.gallery').galleryDialog({linkSelector:'.gallery-link'});
        }


       // var selectedItem=null;
       var bitlyUrl = null,
        encoded = null;
       
        $('.share-link').click(function () {
            shareLink(this);
            return false;
        
        });
       
        $('#share-link').click(function () {
            this.focus();
            this.select();
            return false;
        });

        $('.auto-location').click(function () {
            var button = this,
                gc = new google.maps.Geocoder(),
                loc = null,
                latLng = null;

            navigator.geolocation.getCurrentPosition(function (pos) {
                loc = pos;
                latLng = new google.maps.LatLng(loc.coords.latitude, loc.coords.longitude);

                gc.geocode({'latLng': latLng}, function (results, status){
                    console.log(results);
                    if (status == google.maps.GeocoderStatus.OK && results[1]) {
                        updateLocation(results[1].formatted_address, latLng);
                    } else {
                        updateLocation(loc.coords.latitude + ',' + loc.coords.longitude, latLng);
                    }

                });
            });
            return false;
        });


        $('.other-link a').click(function () {
            $('.other-winners').slideDown();
            $('.other-link').hide('slow');
            $('.unmapped-address').addClass('mapped-address');
            loadMapAndMyLocation();
            return false;
        });

        $('form.text-me-this').submit(function(Event){
            var linkElem = $(this);

            Event.stopPropagation();
            Event.preventDefault();
            var textThisUrl = '/deals/text_deal'
            var phoneToken = $('#phoneToken').val();
            var phoneNumber = $('#phoneNumber').val();
            var dealId = $('#dealId').val();

            $.post(textThisUrl, {
                "token": phoneToken,
                "phone": phoneNumber,
                "dealId": dealId
            }, function (results){
                if (results) {
                    if (results.message_sent) {
                        window.parent.$('#alert_popop').dialog('close');
                        $('#confirm_message')
                        .html('Your message is on its way!')
                        .show('slow')
                        .addClass('alert_message');
                        $('#text_deal_trigger').html('Text This Deal Again');
                    } else {
                        $('#confirm_message')
                        .html(results.errorMessage)
                        .show('slow')
                        .addClass('alert_message');
                        $('#text_deal_trigger').html('There was a problem sending the text message');
                    }
                }
            }
        );
            return false;
        });
        
        $('.clip-this').click(function(){
            var linkElem = $(this);
            var linkHref = linkElem.attr('href');
//            var isClipped = linkElem.hasClass('clipped');

            $.post(
                linkElem.attr('href'), function (results) {
                    if (results["clipped"]) {
                        linkElem.addClass('clipped');
                        linkElem.attr('href', linkHref.replace('clip','unclip'));
                        
                        var scrollPos = $(window).scrollTop();
                        if (scrollPos > 40) {
                            $('#main_utility_nav')
                            .animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, "slow")
                            .addClass('scrolling_nav');
  //                      } else {
//
      //          $('#main_utility_nav')
    //            .animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, "slow")
  //              .removeClass('scrolling_nav');
//                $('#utility_nav_deals_alert').hide();
                        }
                    } else {
                        linkElem.removeClass('clipped');
                        linkElem.attr('href', linkHref.replace('unclip','clip'));
                    }
                    if (results["total"]) {
                        $('#my_deals_count').html('(' + results["total"] + ')');
                        if (parseInt(results["total"]) == 1) {
                            $("#utility_nav_deals_alert")
                            .addClass('alert_message')
                            .show("slow");
                        } else {
                            $("#utility_nav_deals_alert")
                            .removeClass('alert_message')
                            .hide("slow");
                        }
                    } else {
                        $('#my_deals_count').html('');
                        $('#main_utility_nav')
                        .removeClass('scrolling_nav');
                            $("#utility_nav_deals_alert")
                            .removeClass('alert_message')
                            .hide("slow");
                    }
                }
//                }, {"clipped":isClipped}

            );
            return false;
        });

        //catch a scroll, in case we need to create a new status bar
        var windowElem = $(window);
        windowElem.scroll( function (e) {
            if (windowElem.scrollTop() < 40) {
                $('#main_utility_nav')
                .stop()
                .animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, "slow")
                .removeClass('scrolling_nav');
                $('#utility_nav_deals_alert').hide();
            } else {
                var myDealsCount = $('#my_deals_count').html();
                if (myDealsCount != '') {
                    $('#main_utility_nav')
                    .stop()
                    .animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, "slow")
                    .addClass('scrolling_nav');
                }
            }
        })
        $('.location-field').focus(function () {
            var field = $(this);
            if (field.val() == field.attr('default-value')) {
                field.val('');
            }
        });

        $('.location-field').change(function () {
            $('.position-field').val('');
        });

        $('.location-field').blur(function () {
            var field = $(this);
            if ($.trim(field.val()) == '') {
                field.val(field.attr('default-value'));
            }
        });

        $('.location-form').submit(function (Event) {
            submitMapForm(Event);
        });

        $('.location-field').change(function (Event) {
            submitMapForm($('.location-form').submit());
        });
        
        $('.radius').change(function (Event) {
            if ($('.location-field').val() != $('.location-field').attr('default-value') && $('.location-field').val() != '') {
                submitMapForm($('.location-form').submit());
            }
            
        });

        function submitMapForm (mapForm) {

            var gc = new google.maps.Geocoder,
                form = mapForm.target,
                addressField = $('.location-field'),
                positionField = $('.position-field');
            if (positionField.val() && addressField.val()) {
                return true;
            }

            // prevent faulty form submissions
            if (mapForm.type == 'submit') {
                
                mapForm.stopPropagation();
                mapForm.preventDefault();
            }

            if (!positionField.val() && addressField.val()) {
                
                // set a bias for locations from the localBoundary object
                var localBoundarySw = new google.maps.LatLng(localBoundary["southwest"]["latitude"], localBoundary["southwest"]["longitude"]);
                var localBoundaryNe = new google.maps.LatLng(localBoundary["northeast"]["latitude"], localBoundary["northeast"]["longitude"]);
                var localBoundaryLatLngBounds = new google.maps.LatLngBounds(localBoundarySw,localBoundaryNe);

                gc.geocode({'bounds':localBoundaryLatLngBounds, 'address': addressField.val()}, function (results, status) {

                    if (status == google.maps.GeocoderStatus.OK && results[0]) {
                        positionField.val(results[0].geometry.location.toUrlValue());

                        form.submit();
                    } else {
                        //TODO: Handle Geocode errors. Use city centroid?
                    }
                });
            } else {
                console.log('no data');
            }
            return false;
        }

        if(!navigator.geolocation) {
            $('.auto-location').hide();
        }

        if($('.dialog-link').length > 0) {
            $('.dialog-link').click(function (ev) {
                var target=$('#' + $(this).attr('rel')),
                    scroll=window.scrollY,
                    width=$(this).attr('dialog-width') || 600,
                    link = $(this);

                if (link.data('hasDialog')) {
                    target.dialog('open');
                } else {
                    target.dialog(
                        {
                            buttons:    {"Close": function() {$(this).dialog("close");}},
                            modal: true,
                            title: $(this).attr('title'),
                            width: width
                        }
                    );
                    link.data('hasDialog', true);
                }

                ev.stopPropagation();
                return false;
            });
        }
        if($('.dialog-link-alt').length > 0) {
            $('.dialog-link-alt').click(function (ev) {
                var imgElem = $(ev.target);
                if (imgElem.attr('href')) {
                    var linkElem = imgElem;
                } else {
                    var linkElem = imgElem.parent('a');
                }
                // to make sure a func gets run first, add to elements preprocess attr
                if (linkElem.attr('preprocess')) {
                    var preprocess = linkElem.attr('preprocess');
                    window[preprocess]();
                }
                var linkHref = linkElem.attr('href');
                $('#'+ linkElem.attr('rel')).children('iframe').attr('src', linkHref);
                var target=$('#' + linkElem.attr('rel')),
                    scroll=window.scrollY,
                    width=linkElem.attr('dialog-width') || 400,
                    dialogHeight=linkElem.attr('dialog-height') || 350,
                    link = linkElem;

                if (link.data('hasDialog')) {
                    target.dialog('open');
                } else {
                    target.dialog(
                        {
                            buttons:    {"Close": function() {$(this).dialog("close");}},
                            modal: true,
                            title: linkElem.attr('title'),
                            width: width,
                            height: dialogHeight
                        }
                    );
                    link.data('hasDialog', true);
                }
                ev.preventDefault();
                ev.stopPropagation();
                return false;
            });
        }
       
        if($('.autocomplete_inpt').length > 0){
            $('.autocomplete_inpt').focus(function () {
                var focused=this,
                    pos = $(this).position();
                $('.autocomplete_inpt').each(function () {
                    if(this != focused)
                    {
                        if (typeof $(this).autocomplete == 'function') {
                            $(this).autocomplete('destroy');
                        }
                    }
                });
                
                $('.autocomplete_inpt').change(function () {
                    $('#' + $(this).attr('id') + '_force_accept').val(0);

                    if($('.fan-select', $(this).closest('.input_element')).css('display') != 'none') {
                        $('.fan-check', $(this).closest('.input_element')).attr('checked', false);
                        $('.fan-check', $(this).closest('.input_element')).attr('name', 'fanned[]');
                        $('.fan-uncheck', $(this).closest('.input_element')).attr('name', 'fanned[]');
                        $('.fan-uncheck', $(this).closest('.input_element')).attr('disabled','disabled');
                        $('.fan-select', $(this).closest('.input_element')).hide();
                    }
                });
                
                $(this).autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: '/vote/group/suggestions',
                            data: {query: request.term},
                            success: function (data) {
                                var results=[];
                                $.each(data, function () {
                                    if(results.length < 20)
                                    {
                                    results.push({label: this.name, brandId: this.id, value: this.name, valid: this.valid});
                                    }
                                });
                                response(results);
                            },
                            dataType: 'json'
                        });
                    
                    },
                    position: {my : "right top", at: "right bottom"},                    
                    select: function (event, ui) {
                        $(this).val(ui.item.label);
                        $('.fan-check', $(this).closest('.input_element')).attr('name', 'fanned[' + ui.item.brandId + ']');
                        $('.fan-check', $(this).closest('.input_element')).attr('checked', false);
                        $('.fan-uncheck', $(this).closest('.input_element')).attr('name', 'fanned[' + ui.item.brandId + ']');
                        $('.fan-uncheck', $(this).closest('.input_element')).enable();
                        $('.fan-select', $(this).closest('.input_element')).show();
                        return true;
                    },
                    minLength: 2
                }).data( "autocomplete" )._renderItem = function( ul, item ) {
                    return $( "<li></li>" )
                        .data( "item.autocomplete", item )
                        .append("<a>" + item.label + "</a>")
                        .addClass( item.valid === "0" ? 'item-unusable' : '' )
                        .appendTo( ul );
                };

                $('.suggestion-help').css({top: (pos.top - 5) + 'px', left: (pos.left + $(this).width() + 20) + 'px'});
                $('.suggestion-help').show();

            });
        }

        if ($('.brand-vote-button').length > 0) {
            $.getJSON('/vote/allforuser', function (data) {
                var votes = data.votes,
                    status = data.status,
                    singleCategory = $('.single-category').length > 0,
                    categoryId = $('.single-category').attr('categoryId');

                if (status != 'existing' && status !='transferred' && status != 'nouser' && status != 'notfound') {
                    return;
                }

                $('.brand-vote-button').each(function () {
                    var brandName= $(this).attr('brand-name'),
                        brandId= $(this).attr('brand-id'),
                        link = $('<a class="vote-link" id="vote_brand_' + brandId + '" title="Vote for ' + brandName + '" href="/vote/brand/' + brandId + '" ></a>');

                    if (singleCategory) {
                        if (typeof votes[brandId] !== 'undefined' && votes[brandId].indexOf && votes[brandId].indexOf(categoryId) > -1 ) {
                            link.append('<img src="/images/icon_your_pick.png" alt="Your Pick" />');
                        } else {
                            link.append('<img src="/images/icon_vote_for_this.png" alt="Vote for this" />');
                        }
                    } else {
                        if (typeof votes[brandId] !== 'undefined') {
                            link.append('<img src="/images/icon_your_pick.png" alt="Your Pick" />');
                        } else {
                            link.append('<img src="/images/icon_vote_for_this.png" alt="Vote for this" />');
                        }
                    }

                    $(this).append(link);
                });

                $('.vote-link').click(function () {
                    liveDialog(
                        $(this).attr('href') + '?req=' + window.location.href + '%23vote_brand_' + $(this).closest('.brand-vote-button').attr('brand-id'),
                        {
                            modal: true,
                            width: 450,
                            height: 600,
                            title: $(this).attr('title'),
                            beforeClose: function () {
                                window.location.hash='';
                                window.location.reload(true);
                            }
                        }
                    );
                    return false;
                });

                $('.vote-other-form').submit(function () {
                    var obj = this;
                    liveDialog(
                        $(this).attr('action'),
                        {
                            method: 'post',
                            data: $(obj).serialize(),
                            modal: true,
                            width: 450,
                            height: 600,
                            title: 'Vote',
                            beforeClose: function () {
                                window.location.hash='';
                                window.location.reload(true);
                            }

                        }
                    );
                    return false;
                });

                if(window.location.hash.indexOf('vote_brand_') > 0 && !window.location.pathname.match('^/auth')) {
                    $(window.location.hash).click();
                }

            });
        } else {
            $('.vote-other-form').hide();
            //$('.start_ballot').hide();
        }

        $('.suggestion-feedback-link').click(function () {
            liveDialog('/user/feedback', {width: 430, height: 300, title: 'Suggestions Feedback'});
            return false;
        });
        
        $('.generic-feedback-link').click(function () {
            liveDialog('/home/feedback', {width: 440, height: 340, title: 'Suggestions Feedback'});
            return false;
        });

        $('.legal-popup').click(function () {
            liveDialog(
                $(this).attr('href'),
                {
                    buttons:    {"Close": function() {$(this).dialog("close");}},
                    modal: true,
                    width: 800,
                    height: 600,
                    title: $(this).attr('title')
                }
            );
            return false;
        });

        if(window.location.hash=='#vip' && !window.location.pathname.match('^/auth')) {
            $('#vip_footer_trigger_link').click();
        }

    });
    
})(jQuery);

function liveDialog(url, options)
{
//    /layout/set/dialog/
    var dlg = $('<div class="dialog-container" style="display: none"></div>'),
        opts = {layout: 'plain'};

    if (options.data) {
        opts = options.data;
    }

    $(document).append(dlg);

    $.ajax({
        type: options.method || 'get',
        data:  opts,
        dataType: 'html',
        url: url,
        success: function(result, status) {
            dlg.html(result);
            dlg.dialog(options);
            bindDialogEvents(dlg);
        }
    });


}

function bindDialogEvents(dlg)
{
    //Hijack form submissions
    $('form',dlg).submit(function(){
        var data = $(this).serialize(),
            form = $(this);
        //data = data + '&SetSorting=Set';
        $.ajax({
            type: $(this).attr('method'),
            data: data,
            dataType: 'html',
            url: $(this).attr('action'),
            success: function (data) {
                if(data.redirect)
                {
                    dlg.load(data.redirect, {}, function (data){
                        bindDialogEvents(dlg);
                    });
                }
                else
                {
                    form.trigger('dialogFormComplete', [data]);
                    if(form.hasClass('close-on-complete'))
                    {
                        dlg.dialog('close');
                    }
                    else
                    {
                        dlg.html(data);
                        bindDialogEvents(dlg);
                    }

                }
            }
        });

        return false;
    });

    $('.cancel-button', dlg).click(function () {
        dlg.dialog('close');
        return false;
    });

    $('.uibutton', dlg).button();

}

function blurInputDefault (element, defaultValue) {
    if (element.value == '' || element.value == ' ')
        element.value = defaultValue;
}

function clearInputDefault (element, defaultValue) {
    if (element.value == defaultValue) {
        element.value = '';
    }
}

// force an event to trigger a page load on the given link and stop the event from propagating
function forceVisitLink (url, event) {
    event.stopPropagation();
    window.location.href=url;
}


jQuery.fn.galleryDialog = function (opts)
{
    var nextLink = opts.nextLink || '.next-image-link',
        prevLink = opts.prevLink || '.previous-image-link',
        linkSelector = opts.linkSelector || 'a',
        dialogWidth = opts.dialogWidth || 700,
        dialogHeight = opts.dialogHeight || 700,
        dialogClass = opts.dialogClass || 'gallery-dialog',
        dlg = null,
        links = [],
        nextButton = $('<a href="#">Next</a>');
        prevButton = $('<a href="#">Previous</a>');
        obj = this;

    $(linkSelector, this).each(function () {
        links.push($(this));
    });

    $(linkSelector, this).click(function () {
        obj.openDialog($(this).attr('href'), $(this));
        return false;
    });

    this.openDialog = function (href, clickedLink){
        var a = $(this),
            widget = null,
            titlebar = null;
        if(dlg === null)
        {
            dlg = $('<div class="dialog-container" style="display: none"></div>'),
            $(document).append(dlg);
            dlg.dialog({
                    modal: true,
                    dialogClass: dialogClass,
                    width: dialogWidth,
                    height: 'auto',
                    autoOpen: false
            });

            widget = dlg.dialog('widget');
            titlebar = $('.ui-dialog-titlebar', widget);

            titlebar.prepend(nextButton);
            $(nextButton).button({icons: {secondary: 'ui-icon-triangle-1-e'}});


            titlebar.prepend(prevButton);
            $(prevButton).button({icons: {primary: 'ui-icon-triangle-1-w'}});

        }
        obj.loadDialogContent(href, clickedLink);

    };

    this.loadDialogContent = function (href, clickedLink){
        console.log('clickedLink');
        console.log(clickedLink.attr('href'));

        dlg.html('<img class="gallery-popup-image" src="' + href + '" />');
        
        $(nextButton).unbind('click');
        $(nextButton).click(function () {
            var nextLink = null,
                clicked = $(this);

            nextLink = links[0];

            for(i in links) {
                if(!links.hasOwnProperty(i)) {
                    continue;
                }
                if(links[i].attr('href') == clickedLink.attr('href') && i < (links.length - 1)) {
                    nextLink = links[parseInt(i) + 1];
                    break;
                }
            }
            console.log('nextLink');
            console.log(nextLink.attr('href'));
            console.log(nextLink);
            obj.loadDialogContent(nextLink.attr('href'), nextLink);
            return false;
        });

        $(prevButton).unbind('click');
        $(prevButton).click(function () {
            var prevLink = null,
            clicked = $(this);

            prevLink = links[links.length - 1];

            for (i in links) {
                if(!links.hasOwnProperty(i)) {
                    continue;
                }
                if(links[i].attr('href') == clickedLink.attr('href') && i != 0) {
                    prevLink = links[parseInt(i) - 1];
                }
            }
            obj.loadDialogContent(prevLink.attr('href'), prevLink);
            return false;
        });



        dlg.dialog('open');
        /*
        dlg.load(href, null, function (data){

        });
        */

    };
}
