/// <reference path="~/common/compressed/jquery.js" />

String.prototype.format = function() {
    var pattern = /\{\d+\}/g;
    var args = arguments;
    return this.replace(pattern, function(capture) { return args[capture.match(/\d+/)]; });
}

String.prototype.parseDate = function() {

    var s = arguments[0];
    var m = s.match(/^\/Date\((\d+)([-+]\d\d)(\d\d)\)\/$/);
    var date = null;
    if (m)
        date = new Date(1 * m[1] + 3600000 * m[2] + 60000 * m[3]);

    return date;
}


// ---------------
// global variable containing photoset info
var _data = null;
var visiblePhotos = null;

// gets all the data required, starts the google map running and other functions
function StartMapping(sid, search, uid) {

    $("#maploading").css("display", "block");
    if (map != undefined)
        map.clearOverlays();

    var url = "/common/handler/photos.ashx?";

    if (sid != "")
        url = url + "sid=" + sid;
    else
        url = url + "s=" + search + "&uid=" + encodeURI(uid);

    $.getJSON(url,
                function(data) {
                    _data = data;

                    DisplayPhotoCount();

                    if (_data.TotalPhotosGeo > 0) {
                        $("#map").css("display", "block");
                        $("#options").css("display", "block");
                        $("#sets").css("display", "none");
                        $("#showsets").css("display", "block");

                        $.each(_data.popupPhotos, function(i, photo) {
                            var pic1 = new Image(200, 200);
                            pic1.src = photo;
                        });

                        ApplySettings();
                    }
                    else {
                        $("#maploading").css("display", "none");
                        $("#mapempty").css("display", "block");
                        $("#mapempty").html("<div class=\"error-box\"><img src='/images/panels/warning-sad.png' alt='error' title='oh noes... :(' /><p>The set you are trying to map doesn't have any <a class=\"emptygeo\" href=\"/helpers/how-to.aspx?t=geotagging\">geotagged photos</a>. That's ok though, <a class=\"emptygeo\" href=\"/helpers/how-to.aspx?t=geotagging\">find out how to fix this</a>.</p><div class=\"clear\"></div></div>");
                        $(".emptygeo").colorbox({ width: "600px", height: "550px" });
                    }
                });

    ApplyEvents();
}

function BuildGallery(photoset) {

    $("#slider").empty();

    $.each(photoset, function(i, photo) {
        $("#slider").append(photo);
    });
}

// ---------------
// display photo & geophoto count
function DisplayPhotoCount() {

    $("#found").html(_data.TotalPhotos);
    $("#found").css("color", "#00bf00");

    if (_data.TotalPhotosGeo > 0) {
        $("#useable").html(_data.TotalPhotosGeo);
        $("#useable").css("color", "#00bf00");
    }
    else {
        $("#useable").html(_data.TotalPhotosGeo);
        $("#useable").css("color", "#dd0000");
    }

    $("#setName").html(_data.SetName);
    $("#setName").css("color", "#00bf00");

    $("#success").css("display", "block");
}




function ApplyCssTo(id, property, value) {
    if (value != "")
        $(id).css(property, value);
}

function ColourPicker(obj, ids, property, hf) {
    obj.ColorPicker({
        color: hf.val(),
        onShow: function(colpkr) {
            $(colpkr).fadeIn(100);
            return false;
        },
        onHide: function(colpkr) {
            $(colpkr).fadeOut(100);
            return false;
        },
        onChange: function(hsb, hex, rgb) {
            obj.css('background-color', '#' + hex);
            $(hf).val('#' + hex);

            for (ii = 0; ii < property.length; ii++) {
                for (jj = 0; jj < ids.length; jj++) {
                    $(ids[jj]).css(property[ii], "#" + hex);
                }
            }

            $("#btnResetColours").css("display", "block");

        }
    });
}


// --------------------------------------------------
//
//  The Gallery Viewer Javascript
//
// --------------------------------------------------

var pageCount = 0;
var active = 0;
var number = 0;
var width = $('.gallery-viewer').width();
var sliding = false;

// ----------------
//  Applies the Image Slider variables ready for when the user clicks the buttons.
//  These variables will be used in the within the dynamically added functions
//  found in the code below
// ----------------
function StartSlider(photoWidth, visiblePhotos) {

    if (photoWidth == null)
        photoWidth = 60;

    if (visiblePhotos == null)
        visiblePhotos = 4;

    viewer_images = $('.gallery-viewer img');

    if (viewer_images.length > 1) {
        // assign slider functions
        active = 0;
        width = $('.gallery-viewer').width();

        // 0 based page index        
        pageCount = (viewer_images.length / (width / photoWidth));

        if ((pageCount % 1) > 0)
            pageCount = pageCount + 1;

        sliding = false;
    }
}

(function($) {
    $.fn.extend({
        pause: function(milli, type) {
            milli = milli || 1000;
            type = type || "fx";
            return this.queue(type, function() {
                var self = this;
                setTimeout(function() {
                    $(self).dequeue();
                }, milli);
            });
        },
        clearQueue: function(type) {
            return this.each(function() {
                type = type || "fx";
                if (this.queue && this.queue[type]) {
                    this.queue[type].length = 0;
                }
            });
        },
        unpause: $.fn.clearQueue
    });
})(jQuery);

function ResetSlider() {

    // this calculates the distance the slider needs to...erm...slide back to the start
    $('.slider').animate({ "left": "-=" + $('.slider').css("left") }, 'fast', 'swing');

    // reset the slider variables
    active = 0;
    number = 0;
}

function ApplyEventsToGalleryButtons() {
    $('.move').each(function(i) {

        $(this).click(function() {
            if (sliding) { return false; } // don't do anything if we're already on the move
            number = 0;
            var id = $(this).attr('id');
            if (id == "move-left") {
                if ((active - 1) >= 0)
                    number = active - 1;
                else
                    return;
            }

            if (id == "move-right") {
                if ((active + 1) <= pageCount - 1)
                    number = active + 1;
                else
                    return;
            }

            sliding = true; // enter sliding mode
            distance = ((active * width) - (number * width));

            $('.slider').animate({ "left": '+=' + distance }, 'slow', 'swing'); // slide...

            active = number; // set new active
            sliding = false; // exit sliding mode
            return false; // return false so link doesn't activate
        });
    });
}

function ApplyEventsToMapPointLabels() {
    $("label.pinpoint").mouseover(function() {
        if (!($(this).hasClass("selected")))
            $(this).addClass("over");
    });

    $("label.pinpoint").mouseout(function() {
        if (!($(this).hasClass("selected")))
            $(this).removeClass("over");
    });

    $("label.pinpoint").click(function() {
        $("label.pinpoint").removeClass("selected");
        $("label.pinpoint").removeClass("over");
        $(this).addClass("selected");
    });
}

// function applys events to the different buttons and <div> tags
function ApplyEvents() {
    ApplyEventsToGalleryButtons();
    ApplyEventsToMapPointLabels();
}

// STEP ONE JAVASCRIPT

// ---------------
// loads sets on step one
// value = flickr credential
// type = flick credential type (username|email|url)
function LoadSets(value, type) {

    $(".box-sml .nosets").css({ display: "none" });
    $("#sets").html("<div align=\"center\"><p>Talking to flickr, hang on a sec...</p><p><img src=\"/images/loader.gif\" alt=\"won't be long\" /></p></div>");
    $("#sets").css("display", "block");
    $("#searches").css("display", "none");
    $.getJSON("/common/handler/sets.ashx?v=" + value + "&t=" + type,
                function(data) {                
                    $("#sets").html(data.Html);
                    $("#hfUserId").val(data.UserId);
                    $("#searched").css("display", "block");
                });

    return true;
}

function Search() {
    var searchTerm = encodeURI($("#searchField").val());
    $("#sets").html("<div align=\"center\"><p>Talking to flickr, hang on a sec...</p><p><img src=\"/images/loader.gif\" alt=\"won't be long\" /></p></div>");
    $("#searches").html("<div align=\"center\"><p>Talking to flickr, hang on a sec...</p><p><img src=\"/images/loader.gif\" alt=\"won't be long\" /></p></div>");
    $("#searches").load("/common/handler/search.ashx?v=" + searchTerm + "&uid=" + $("#hfUserId").val(), function() { $("#sets").css("display", "none"); $("#searches").css("display", "block"); });
}

// ---------------
// handles step one form postback - form will be valid by the time we get here
function StepOneClick(obj) {

    if ($("#txtFlickrEmail").val() != "") {
        setFlickrCookie($("#txtFlickrEmail").val(), 2);
        return LoadSets(encodeURI($("#txtFlickrEmail").val()), "email");
    }

    if ($("#txtFlickrURL").val()) {
        setFlickrCookie($("#txtFlickrURL").val(), 3);
        return LoadSets(encodeURI($("#txtFlickrURL").val()), "url");
    }

    if ($("#txtFlickrUserName").val() != "") {
        setFlickrCookie($("#txtFlickrUserName").val(), 1);
        return LoadSets(encodeURI($("#txtFlickrUserName").val()), "username");
    }
}

function setFlickrCookie(val, box) {
    if ($("#cbRemember").val()) {
        $.cookie('imapflickr', val + "," + box, { expires: 365, path: '/' });
    }
}



function getFlickrCookie() {

    var value = $.cookie('imapflickr');
    if (value != "" && value != null) {
        var split = value.split(",");
        switch (parseInt(split[1])) {
            case 1:
                $("#txtFlickrUserName").val(split[0]);
                break;
            case 2:
                $("#txtFlickrEmail").val(split[0]);
                break;
            case 3:
                $("#txtFlickrURL").val(split[0]);
                break;
        }
    }
}



// END STEP ONE JAVASCRIPT

function select_text(el) {
    if (el.createTextRange) {
        var oRange = el.createTextRange();
        oRange.moveStart("character", 0);
        oRange.moveEnd("character", el.value.length);
        oRange.select();
    }
    else if (el.setSelectionRange) {
        el.setSelectionRange(0, el.value.length);
    }
    el.focus();
}

// ACCOUNTS PAGE JAVASCRIPT

// global variable containing user map info
var _usermaps = null;

// loads user map data in the background
function LoadMaps(user_id) {
    $.getJSON("/common/handler/get-user-maps.ashx?uid=" + user_id,
                function(data) {
                    _usermaps = data;
                });
}

// select text function moved to js file

// --------------------------
// display http link to user generated map
function DisplayLink(map_id) {

    $("#embedd").css("display", "none");

    var map = GetMap(map_id);
    if (map != null) {

        var map_domain = window.location.hostname;
        map_domain = map_domain.replace(/co\.uk/, "com");
        map_domain = map_domain.replace(/www\./, "");
        var map_link = "http://" + map_domain + "/" + map.ShortURL;

        var map_html = "<p>Use URLs below in your blog, Facebook page, twitter etc to link to your map:<p>";

        map_html += "<p><strong>Standard:<br /></strong><input type='text' id='embedd-html' readonly='readonly' value='" + map_link + "' style='width:98%' onclick='select_text(this);' onkeyup='select_text(this);' class='share'/></p>";

        map_html += "<ul class='nav-tools'><li class='m06'><a href=\"" + map_link + "\" target=\"_blank\"><span>Preview</span></a></li></ul>";

        map_html += "<p style='clear:both;margin-top:5px;'><strong>Full screen:<br /></strong><input type='text' id='embedd-html' readonly='readonly' value='" + map_link + "/large.aspx' style='width:98%'  onclick='select_text(this);' onkeyup='select_text(this);' class='share'/></p>";

        map_html += "<ul class='nav-tools'><li class='m06'><a href=\"" + map_link + "/large.aspx\" target=\"_blank\"><span>Preview</span></a></li></ul>";

        $("h2.embedd-option").html("Link to your map:<br />'" + map.Name + "'");
        $("div.embedd-detail").html(map_html);

    }
    else {
        $("h2.embedd-option").html("Error");
        $("div.embedd-detail").html("<p>Oh dear.. something went wrong finding your map information</p>");
    }
    $("#embedd").fadeIn("medium");
    select_text(document.getElementById("embedd-html"));

}

// --------------------------
// display embeddable HTML for user generated map
function DisplayHTML(map_id) {

    $("#embedd").css("display", "none");

    var map = GetMap(map_id);
    if (map != null) {
        $("h2.embedd-option").html("Embedd your map:<br />'" + map.Name + "'");

        var map_html = "<p>Use the HTML below to embedd your map in a blog or website:<p><textarea rows='8' id='embedd-html' style='width:98%' readonly='readonly' onclick='select_text(this);' onkeyup='select_text(this);' class='share'>" + map.iFrame + "</textarea>";
        // map_html += "<ul class='nav-tools'><li class='m05'><a href=\"#\" onclick='SelectText(\"#embedd-html\")'><span>Copy</span></a></li></ul>";

        $("div.embedd-detail").html(map_html);

    }
    else {
        $("h2.embedd-option").html("Error");
        $("div.embedd-detail").html("<p>Oh dear.. something went wrong finding your map information</p>");
    }

    $("#embedd").fadeIn("medium");
    select_text(document.getElementById("embedd-html"));

}


// ------------------
// returns one map object based on map_id
function GetMap(map_id) {

    var found = null;
    $.each(_usermaps, function(usermap) {
        if (_usermaps[usermap].ID == map_id) {
            found = _usermaps[usermap];
        }
    });
    return found;

}

// END ACCOUNTS PAGE JAVASCRIPT

/* FACEBOOK JAVASCRIPT */
function HasPermission(showPermissions, facebookId) {
    LoggedInProperly(showPermissions);
}

function isNullOrEmpty(value)
{
	if(value == null)
		return true;
		
	if(value == undefined)
		return true;
		
	if(value == "")
		return true;
		
	return false;	
}

function DisplayButtons(facebookId) {

    if (!isNullOrEmpty(facebookId)) {
        //  we have a Facebook userId for the current logged in iMapFlickr user, so we don't need to do anything else
        // it doesn't matter if the person that is currently logged into facebook is different, we won't let them connect again.            
        $("#pnlPublicComputer").css("display", "none");
        $("#facebookConnect").css("display", "none");
        $("#facebookThanks").css("display", "block");
    }
    else {
        // the person currently logged in to iMapFlickr doesn't have an associated Facebook ID
        // show the connect button
        $("#facebookConnect").css("display", "block");
        $("#facebookThanks").css("display", "none");        
    }
}

function GrantPermissions() {
    FB.Facebook.apiClient.users_hasAppPermission('offline_access', function(result) {
        if (result > 0) {
            window.location = "http://" + window.location.hostname+ "/accounts/add-facebook.aspx"; // don't reload...redirect back
        }
        else {
            FB.Connect.showPermissionDialog("status_update,offline_access", function(result) {
                if (result.indexOf("offline_access") > 0) {
                    window.location = "http://" + window.location.hostname + "/accounts/add-facebook.aspx"; // don't reload...redirect back
                }
            });
        }
    });
}

var _time = -1;

function Reconnect() {
    FB.ensureInit(function() {
        FB.Connect.ifUserConnected(function(ex) {
            FB.Connect.logout(function(ex) {
                window.location = window.location; // don't reload...redirect back
            });
        }, "facebook.aspx");
    });
}

/* COUNTER */
function imposeMaxLength(obj, maxLen, display) {
    
    $("#" + display).html(maxLen - obj.value.length);
    if (obj.value.length > maxLen) {
        obj.value = obj.value.substring(0, maxLen - 1)
    }
    return (obj.value.length <= maxLen);
    
}