//Local variables
var loadRequest = true;
var locationTag = "";
var locationID = -1;
var cuisineTag = "";
var idTag = "";
var maxPicWidth = 166;
var maxPicHeight = 151;
var entryID = 0;
var entryUrl = "";
ZeroClipboard.setMoviePath("/scripts/jclipboard/ZeroClipboard.swf");
var fancyBoxConfig = { 
    'centerOnScroll': true,
    'overlayShow': true,
    'hideOnContentClick': false,
    'hideOnOverlayClick': true,
    'frameWidth': 750,
    'frameHeight': 500,
    'padding': 0,
    'callbackOnShow': fBoxActionsDelegate
};

//Event Handlers
$(document).ready(function() {

    //Initial Load
    performLoad(false);

    //Fancybox
    loadFancyBox();

    //Scrolling events
    $(window).scroll(function() {
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300) {
            //Execute the query and load the Divs
            var lastId = $(".products ul li").length - 1;
            var excluded = -1;
            performQuery(lastId, excluded, 20);
        }     
    });

    //GetSatisfaction
    $.xLazyLoader({
        css: '/css/feedback-GC.css',
        success: function() {
            $('body').append("<a href='/getsatisfaction.htm' id='fdbk_tab' class='fdbk_tab_overlay iframe' style='background-color:#222'>FEEDBACK </a>");
            $('#fdbk_tab').fancybox({ 'centerOnScroll': true, 'frameWidth': 440, 'frameHeight': 320, 'padding': 0, 'overlayShow': true });
            
        }
    });

});

//Queries the daFoodie Database
function performQuery(startOffset, excludeArr, qty) {
    //Show the fancybox timer icon
    $.fn.fancybox.showLoading();

    var JSONQuery = "/Query.aspx"
    var JsonParse = "dataRequest = { start: startOffset, num: qty ";
    if (cuisineTag != undefined && cuisineTag.length > 0)
        JsonParse += ", cuis: cuisineTag";
    if (locationID != undefined && locationID.length > 0 && locationID != -1)
        JsonParse += ", loc: locationID";
    if (cityID != undefined && cityID > 0)
        JsonParse += ", city: cityID";
    JsonParse += "};";
    eval(JsonParse);

    $.getJSON(JSONQuery, dataRequest,
                function(data) {
                    //If the query doesn't return anything show the sorry sign
                    if (data.length == 0 && loadRequest) {
                        cuisineTag = "";
                        locationID = -1;
                        performQuery(-1, -1, 20);
                    }
                    else {
                        $.each(data, function(i, post) {
                            //Displaying new pics
                            addNewDiv(this, i + startOffset);
                        });

                        //Interaction
                        addInteraction();

                        //Hide the fancybox loading icon
                        $.fn.fancybox.hideLoading();
                        loadRequest = false;
                    }
                });
}

//loads the page with the first results
function performLoad(resetLocations) {
    //Check if this is the first call
    loadRequest = true;

    if (resetLocations) {
        //Reset location
        locationTag = cityTag + " (All)";
        $('#dropLocations .aLink').text(locationTag);
        locationID = 0;

        //Refresh locations for given city
        var dropLocations = $('#dropLocations ul');
        dropLocations.empty();
        dropLocations.append("<li><a href='0'>" + cityTag + " (All)</a></li>");
        $.ajax({
            type: 'GET',
            url: '/queryDB.aspx',
            dataType: 'json',
            success: function(data) {
                $.each(data, function(i, location) {
                    var newLi = "<li><a href='" + location.LocationID + "'>" + location.LocationName + "</a></li>";
                    dropLocations.append(newLi);
                });
            },
            error: function() {
                //TODO: Add Error Message
            },
            data: { type: "locationsbycity", id: cityID },
            async: false
        });
    }

    //Filtering
    AddDropDownBehaviour();
    
    //Query
    var docHeight = $(document).height();
    var rowNumber = Math.round(docHeight / 100);
    $('.products ul').empty();
    performQuery(0, -1, 4 * rowNumber);
}

//adds a new picture to the post collection
function addNewDiv(post, i) {
    //Caption Truncate
    post.Caption = truncateCaption(post.Caption);

    //Check if post already is present on page
    var exists = $(".products ul li#" + post.ID);
    if (exists.length > 0)
        return;

    //Add new post to the page
    var newLi = "";

    if (post.ID > 5) {
        newLi = "<li id='" + post.ID + "'> <div class='boxgrid captionfull'><a href='/EntryView.aspx' id='l" + post.ID + "'><img width=166 height=151 /></a>"
                    + "<span class=\"cover boxcaption\" style=\" top:270px; padding:5px; \"><span class='capTitle'>" + post.Caption + "</span>" + "<br />"
                    + post.RestaurantName + "</span></div></li>";
    }
    else {
        newLi = "<li id='" + post.ID + "'> <div class='boxgrid captionfull'><img width=166 height=151 /></div></li>";
    }
    
    var lastId = $(".products ul li:last");
    if (lastId.length == 0)
        $('.products ul').append(newLi);
    else
        lastId.after(newLi);

    //Lazy Load the image and show
    $.xLazyLoader({
        img: post.PhotoUrlSmall,
        success: function() {
            var currImg = $('#' + post.ID + ' img');
            currImg.attr("src", post.PhotoUrlSmall);
            currImg.attr("alt", post.Caption + ' - ' + post.RestaurantName + ' - ' + post.Location);
        },
        error: function() {
            var x = 0;
        }
    });

    //Progress Icon
    lastId.hide();
    lastId.fadeIn("slow");
}

//Truncates all captions that exceed 20 characters
function truncateCaption(caption) {
    if (caption.length > 19) {
        var pos = 0, lastPos = 0;
        while (pos > -1) {
            pos = caption.indexOf(" ", pos + 1);
            if (pos > -1)
                lastPos = pos;
        }
        if (lastPos < 20 && lastPos > 15)
            caption = caption.substring(0, lastPos) + "...";
        else
            caption = caption.substring(0, 18) + "...";
    }
    return caption;
}

//Adss interaction after each div is loaded
function addInteraction() {
    //Slide Effect
    $('.boxgrid.captionfull').hover(function() {
        $(".cover", this).stop().animate({ top: '100px' }, { queue: false, duration: 160 });
    }, function() {
        $(".cover", this).stop().animate({ top: '200px' }, { queue: false, duration: 160 });
    });

    //CSS Load 
    $.xLazyLoader({ css: ['/scripts/jclipboard/Style-GC.css', '/css/lightbox-GC.css'] });

    //Fancybox
    var entryLink = $('.products ul li a');
    entryLink.fancybox(fancyBoxConfig);
    entryLink.click(function() {
        $('#fancy_content').data('entryId', this.id.substring(1));
    });
}

//Gets parameters from the url query string
function getUrlVars() {
    var vars = [], hash;

    //regular id parameters
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    //MVC Style params
    if (idTag != undefined && idTag.length > 0) {
        vars['id'] = idTag;
    }
    return vars;
}

//Applies dropdown behaviour after page is loaded
function AddDropDownBehaviour() {
    $('#dropCuisines li a').click(function() {
        var currentTag = $('#dropCuisines .aLink').text();
        var selTag = (this.innerText == undefined) ? this.innerHTML : this.innerText;

        if (selTag == "All")
            cuisineTag = "";
        else
            cuisineTag = selTag;
        $('#dropCuisines .aLink').text(selTag);

        if (currentTag != selTag)
            performLoad(false);

        $('#dropCuisines dd ul').hide();
        SetCursorTop();
        return false;
    });

    $('#dropLocations li a').click(function() {
        var currentTag = $('#dropLocations .aLink').text();
        var selTag = (this.innerText == undefined) ? this.innerHTML : this.innerText;

        if (selTag.indexOf("(All)") != -1) 
        {
            locationTag = "";
            locationID = -1;
        }
        else {
            locationTag = selTag;
            locationID = this.href.substr(this.href.lastIndexOf('/') + 1);
        }
        $('#dropLocations .aLink').text(selTag);

        if (currentTag != selTag) {
            performLoad(false);
        }

        $('#dropLocations dd ul').hide();
        SetCursorTop();
        return false;
    });

    //Animations
    $('.dropdown').click(function() {
        $('#' + this.id + ' dd ul').slideDown("normal");
    });
    $('dropdown dd ul').mouseout(function() {
        this.hide();
    });
    $(document).click(function() {
        $('.dropdown dd ul').hide();
    });
}

//Check for parameters and loads a fancybox if needed
function loadFancyBox() {
    $('#paramFancyBox').hide();
    $('#TweetitOauth').hide().fancybox(fancyBoxConfig);

    //initial box
    var urlParams = getUrlVars();
    var entryId = urlParams['id'];
    if (entryId != undefined && entryId.length > 0) {
        //In case CSS for entry box is not loaded
        $.xLazyLoader({ css: ['/scripts/jclipboard/Style-GC.css', '/css/lightbox-GC.css'] });

        //Fancybox config
        var placeholder = $('#paramFancyBox');
        placeholder[0].href = "/EntryView.aspx?id=" + entryId;
        placeholder.fancybox(fancyBoxConfig);
        $('#fancy_content').data('entryId', entryId);
        $('#fancy_content').data('dfdo', true);
        placeholder.trigger('click');
    }

//    //Fancybox for submit box
//    var agent = navigator.userAgent.toLowerCase();
//    var submitPic = $('.submit_pic');
//    if (agent.indexOf('iphone') != -1 || agent.indexOf('ipad') != -1 || agent.indexOf('ipod') != -1) {
//        submitPic.hide();
//    }
//    else {
//        submitPic[0].href = "/SubmitChoose.htm?city=" + cityID;
//        submitPic.fancybox(
//        {   'frameWidth': 370,
//            'frameHeight': 380,
//            'centerOnScroll': true,
//            'overlayShow': true,
//            'hideOnContentClick': false,
//            'hideOnOverlayClick': true,
//            'padding': 0,
//            'callbackOnShow': submitDelegate
//        });
//    }

//    //Fancybox for city change
//    $('.cities').fancybox(
//    {
//        'frameWidth': 565,
//        'frameHeight': 410,
//        'centerOnScroll': true,
//        'overlayShow': true,
//        'hideOnContentClick': false,
//        'hideOnOverlayClick': true,
//        'padding': 0,
//        'callbackOnShow': cityDelegate
//    });

    //Fancybox for advertise form
    $('#advertiselink').fancybox({
        'frameWidth': 575,
        'frameHeight': 480,
        'centerOnScroll': true,
        'overlayShow': true,
        'padding': 0
    });
    
}

//Fancybox delegate calls (executes after the fancybox loads)
function fBoxActionsDelegate() {
    var entryID = $('#fancy_content').data('entryId');
    loadFormElements(entryID);
}
function submitDelegate() {
    $('#lnkUpload').fancybox({ 'centerOnScroll': true, 'frameWidth': 500, 'frameHeight': 580, 'padding': 0, 'overlayShow': true });
}
function cityDelegate() {
    //Actions for selected city
    $('.topcities a').click(function() {
        var cityName = this.pathname.indexOf("/") != -1 ? this.pathname.substring(1) : this.pathname;
        cityID = cityName.substring(0, cityName.indexOf("-"));
        cityTag = cityName.substring(cityName.indexOf("-") + 1).replace("_", " ");
        $.fn.fancybox.close();
        $('.submit_pic')[0].href = "/SubmitChoose.htm?city=" + cityID;
        performLoad(true);
        return false;
    });

    //Watermark for textboxes
    $.xLazyLoader({
        js: '/scripts/jquery.watermark.js',
        success: function() {
            $('.text_field').watermark('watermark', 'Email Address');
            $('.text_field_small').watermark('watermark', 'ZIP Code');     
        }
    });
}

//Sets the screen to the beginning of the document
function SetCursorTop() {
    $('html, body').animate({ scrollTop: 0 }, 'slow');
}


//******* LIGHTBOX / ENTRY FUNCTIONALITY ******* //

//Sets actions for the entry lightbox
function setFancyBoxActions() {

    //Url that leads back to this entry
    setEntryurl();
    
    //Copy, twitter, facebook
    registerCopyButton(entryUrl);
    registerTwitterButton(entryUrl);
    registerFacebookButton(entryUrl);

    //Next button
    
    if ($('#fancy_content').data('dfdo') == undefined) {
        $('#next-food').removeClass('hiddenDiv');
    }

    var nextHasEvents = $('#next-food').data('events');
    if (nextHasEvents == undefined) {
        $('#next-food').click(function() {
            var imgObject = $('#imgMainPicture');
            var entryID = $('#fancy_content').data('entryId');
            var nextLi = $('#' + entryID).next();
            if (nextLi.length > 0) {
                loadFormElements(nextLi[0].id);
            }
            else {
                $('#next-food').hide();
            }
            return false;
        });
    }

//    var foo = $('#next-food').data('events')
//    if (foo == undefined) {
//        $('#next-food').click(function() {
//            var imgObject = $('#imgMainPicture');
//            var entryID = $('#fancy_content').data('entryId');
//            var nextLi = $('#' + entryID).next();
//            if (nextLi.length > 0) {
//                loadFormElements(nextLi[0].id);
//            }
//            else {
//                $('#next-food').hide();
//            }
//            return false;
//        });
//    }
    

    //Google Map-it
    $('#googlemap').fancybox({ 'centerOnScroll': true, 'frameWidth': 750, 'frameHeight': 500, 'padding': 0, 'overlayShow': true });
    //Advertisement
    $('#advertiseform').fancybox({ 'centerOnScroll': true, 'frameWidth': 500, 'frameHeight': 580, 'padding': 20, 'overlayShow': true });
}

//Queries the database and fills the entry object
function loadFormElements(entryID) {
    $('#fancy_content').data('entryId', entryID);

    //variables
    var JSONQuery = "/QueryItem.aspx"
    var imgObject = $('#imgMainPicture');
    var innerTitle = $('.title_inner');
    var innerRest = $('.title_inner_restaurant');

    $.ajax({
        type: 'GET',
        url: JSONQuery,
        dataType: 'json',
        success: function(data) {
            //Show Waiting Icon
            imgObject.attr('src', '/images/loader.gif');
            imgObject.attr('width', 31).attr('height', 31);

            //Screen elements
            $.xLazyLoader({
                img: data.PhotoUrlMed,
                success: function() {
                    imgObject.attr('src', data.PhotoUrlMed);
                    imgObject.attr('width', 500).attr('height', 375);
                    imgObject.attr('alt', data.Caption + ' - ' + data.RestaurantName + ' - ' + data.Location);
                    innerTitle.text(data.Caption);
                    innerRest.text(data.RestaurantName);
                    imgObject.hide().fadeIn("slow");
                    innerTitle.hide().fadeIn("slow");
                    innerRest.hide().fadeIn("slow");

                    //Mapping Url
                    $('#googlemap')[0].href = "/DrawMap.aspx?entryId=" + entryID + "&nam=" + innerRest.text();
                    //Short Url
                    $('#fancy_content').data('shortUrl', data.ShortUrl);

                    //Set controls
                    setFancyBoxActions()
                },
                error: function() {
                    //TODO: Add error messages
                }
            });
        },
        error: function() {
            imgObject.hide();
            innerTitle.text("The link you typed seems to be broken");
            //$.fn.fancybox.close();
        },
        data: { 'id': entryID },
        async: false
    });
}

//Manages Copy to Clipboard Functionality
function registerCopyButton(entryUrl) {
    var clip = new ZeroClipboard.Client();
    clip.setText(entryUrl);
    clip.glue('copy-it');
    return false;
}

//Sets the current entry URL for Facebook, Twitter and Copy buttons
function setEntryurl() {
    var entryID = $('#fancy_content').data('entryId');
    var shortUrl = $('#fancy_content').data('shortUrl');
    entryUrl = "http://df.do/";
    if (shortUrl != undefined && shortUrl.length > 0) {
        entryUrl += shortUrl;
    }
    else {
        if (entryID.length > 0 && entryID != "0") {
            entryUrl += entryID;
        }
    }
}

//Send to twitter Functionality
function registerTwitterButton(entryUrl) {
    var btnTweet = $('a#tweet-it');
    btnTweet[0].href = "TweetitOauth.aspx?id=" + entryUrl;
    btnTweet.fancybox({ 'centerOnScroll': true, 'frameWidth': 450, 'frameHeight': 320, 'padding': 0, 'overlayShow': true });
}

//Register event for Facebook Button
function registerFacebookButton(entryUrl) {
    $('a#facebook-it').click(function() {
        var apiKey = "40f27e7dd7d09510252f2bd86e27f719";
        var channel = "/api/xd_receiver.htm";
        var imageUrl = $('#imgMainPicture')[0].src;

        FB.init(apiKey, channel)
        FB.ensureInit(function() {
            var attachment = { 'media': [{ 'type': 'image',
                'src': imageUrl,
                'href': entryUrl}]
            };
            FB.Connect.streamPublish('I just decided what to eat on dafoodie.com!',
             attachment, null, null, 'Share with other foodies!');
        });
    });
}
