﻿var aniSpeed = 'medium';
var $map = null;

function initializeS2S(location){
    initialize();
    S2SInterface.bindLikes();
    S2SInterface.bindToolTips();
    
    if (!S2SState.isLoggedIn) {
        initLogin();
    }
    S2SInterface.bindOverlays();

    $(".scroll").click(function (e) {
        scrollWin($(this).attr("href"));
        return false;
    });

    $("input[type=text]").click(function (e) {
        $(this).select();
    });

    $("#get-location").click(function (e) {
        $(this).attr("disabled", "disabled");
        getBrowserLocation();
        e.preventDefault();
        $(this).removeAttr("disabled");
        return false;
    });

    if (null != $map) {
        addGoogleMapsListener();
    }

    if (location !== "") {
        $("#main-search").val(location);
    }
}


var scrollWin = function (selector) {
    $('html, body').animate({
        scrollTop: $(selector).offset().top
    }, 2000);
}


function initLogin() {

    S2SForm.bindAjaxForm({
        theForm: "#login-form",
        errorContainer: "#login-errors",
        validationRules: {
            loginname: "required",
            loginpass: "required"
        },
        validationMessages: {
            loginname: "Please enter your email or username.",
            loginpass: "Password is required."
        },
        activityContainer: "#login-activity"
    },
        function (response) {
            if (window.location.href.toLowerCase().indexOf("/login") == -1) {
                window.location.href = window.location.href;
            }
            else {
                window.location.href = response.RedirectUrl !== "" ? response.RedirectUrl : window.location.href;
            }
        });
}

var currentPage = 0;

function getSpotsCallBack(data) {

    S2SMap.clearMarkers();

    S2SMap.displaySpotMarkers($map, data.Items, false);
    S2SInterface.displaySpots(data.Items);
    S2SInterface.displayPagination(data.Pagination, function (curPage) {
        currentPage = curPage;
        reloadUsers = false;
        getSpots();
    });
    S2SInterface.hideLoader();
}


var getSpotsTimeout;

function parseHash() {
    var parameters = $.deparam.fragment(window.location.href);

    if (undefined != parameters.loc) {
        return parameters;
    } else {
        return null;
    }
}


function addGoogleMapsListener() {

    google.maps.event.addListener($map, 'bounds_changed', function () {
        if (getSpotsTimeout) {
            clearTimeout(getSpotsTimeout);
        }

        reloadUsers = true;
        getSpotsTimeout = setTimeout(getSpots, 1000);
    });
}


var reloadUsers = true;
function getSpots() {
    S2SInterface.showLoader("#spot-container", "Loading Spots");
    S2SMap.getSpots(null, currentPage + 1, function (data) {
        getSpotsCallBack(data);

        if (reloadUsers) {
            S2SInterface.showLoader("#user-container", "Loading Top Users");
            S2SMap.getTopUsers(null, null, function (data) {
                S2SInterface.displayUsers(data.Items);
                S2SInterface.hideLoader();
            });
        }

    });
}

function setMainSearchText(location, setLocation) {

    $("#main-search").val(location);

    if (setLocation) {
        S2SInterface.setCurrentLocation(location);
    }
    
}

function getBrowserLocation() {

    S2SInterface.showLoader("#main-map", "Locating");
    S2SMap.detectLocation(function (location) {
        S2SMap.reverseGeoCode(location, function (results) {
            S2SMap.centerMap($map, results[0].geometry);
            var addressInfo = S2SMap.parseAddress(results);
            setMainSearchText(addressInfo.formattedAddress, true);
        });
        S2SInterface.hideLoader();
    });
}

function initialize() {

    S2SInterface.bindMainSearch($("#main-search-form"), function (results, formattedAddress) {

        if ($map !== undefined && $map != null) {
            S2SMap.centerMap($map, results[0].geometry, null, function () {
                setMainSearchText(formattedAddress, true);
            });
        } else {
            var uri = "/#loc=" + formattedAddress + "&lat=" + results[0].geometry.location.lat() + "&lng=" + results[0].geometry.location.lng();
            window.location.href = encodeURI(uri);
        }
    });
}

function getRouteUrl(name) {

    for (var i = 0; i < scriptRoutes.length; i++) {
        if (scriptRoutes[i].ActionName.toLowerCase() === name.toLowerCase()) {
            return scriptRoutes[i].Url;
        }
    }
}


var ObjectIdConverter = {
    hexDigits: '0123456789ABCDEF',

    toHexString: function(list) {
        var translated = "";
        for (var i = 0; i < list.length; i++) {
            translated += this.dec2hex(list[i]);
        }
        return translated.toLowerCase();
    },
    dec2hex: function(dec) {
        return (this.hexDigits[dec >> 4] + this.hexDigits[dec & 15]);
    }
}

$.postJSON = function(url, data, callback) {
    return $.ajax({
        'type': 'POST',
        'url': url,
        'contentType': 'application/json',
        'data': data,
        'dataType': 'json',
        'success': callback
    });
};




function isKeyCodeAlphaNumeric(key) {
    var keychar = String.fromCharCode(key);
    return isAlphaNumeric(keychar);
}
function isAlphaNumeric(v) {
    if (/[0-9A-Za-z]*/.test(v.value)) {
        return true;
    }
    return false;
}


/** google maps **/
var geocoder;
var map;
var maps = [];

/*
    mapContainer = element that contains the map, <div>
    latlng = google location object
    mapId = null if not main map
*/
function getZoomLevel(zoom) {

    switch (zoom) {
        case "WORLD":
            return 1;
            break;
        case "CONTINENTS":
            return 2;
            break;
        case "COUNTRY":
            return 3;
            break;
    }
}

String.prototype.trim = function() {
    return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
}

String.prototype.startsWith = function (str) {
    return (this.match("^" + str) == str) 
}

String.prototype.endsWith = function (str) {
    return (this.match(str + "$") == str) 
}

String.prototype.toLegalUrl = function () {
    return this.replace(/[^a-zA-Z0-9]/g, '-')
               .replace(/-+/g, '-')
               .toLowerCase();
}

String.prototype.toPreview = function (words, moreText, url) {
    var set = this.split(" ", words);
    if (set.length >= words) {
        return set.join(" ") + "... <a title='More' href='" + url + "'>" + moreText + "</a>";
    } else {
        return this;
    }
}

/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}




