(function($) {
    var map = new Array();
    $.Watermark = {
        ShowAll: function() {
            for (var i = 0; i < map.length; i++) {
                if (map[i].obj.val() == "") {
                    map[i].obj.val(map[i].text);
                    map[i].obj.css("color", map[i].WatermarkColor);
                } else {
                    map[i].obj.css("color", map[i].DefaultColor);
                }
            }
        },
        HideAll: function() {
            for (var i = 0; i < map.length; i++) {
                if (map[i].obj.val() == map[i].text)
                    map[i].obj.val("");
            }
        }
    }

    $.fn.Watermark = function(text, color) {
        //if (!color)

        color = "#aaaaaa";
            
        return this.each(
			function() {
			    var input = $(this);
			    var defaultColor = input.css("color");
			    map[map.length] = { text: text, obj: input, DefaultColor: defaultColor, WatermarkColor: color };
			    function clearMessage() {
			        if (input.val() == text)
			            input.val("");
			        input.css("color", defaultColor);
			    }

			    function insertMessage() {
			        if (input.val().length == 0 || input.val() == text) {
			            input.val(text);
			            input.css("color", color);
			        } else
			            input.css("color", defaultColor);
			    }

			    input.focus(clearMessage);
			    input.blur(insertMessage);
			    input.change(insertMessage);

			    insertMessage();
			}
		);
    };
})(jQuery);

function setToolTipParams(name, tipWidth) {
    if (tipWidth == null)
        tipWidth = 350;
    
    var el = $('#' + name);
    if (el.attr('title') != '' && el.attr('title') != 'undefined') {
        $('#' + name).bt({
            showTip: function(box) {
                $(box).fadeIn(500);
            },                 
            fill: '#ECEBEB',
            width: tipWidth,
            //positions: ['right'],
            contentSelector: "$(this).attr('title')" 
        });        
    }
    
}

var selectCategoryDialog = null
var fogotPassword = null
var registerForm = null
var profileForm = null
var reportPoint = null
var createPointDialog = null
var createLocationDialog = null
var createRouteDialog = null
var createEventDialog = null
var createGroup = null
var downloadToMobile = null
var sharePoint = null
var login = null
var loginAsk = null
var selectItemTypeDialog = null
var rateDialog = null
var commentDialog = null

var popup_names = new Array(    
    "#FogotPopupContact",
    "#LoginPopupContact",
    "#registerPopupContact",
    "#profilePopupContact",
    "#reportPointPopupContact",
    "#createPointPopupContact",
    "#createLocationDialog",
    "#ratePopupDialog",
    "#commentsPopupDialog",
    "#createGroupPopupContact",
    "#createEventPopupContact",
    "#selectCategoryPopupDialog",
    "#loginAskContact"
);

var create_popup_ids = new Array(
    "#createPointPopupContact",
    "#createLocationDialog",
    "#createRoutePopupContact",
    "#createEventPopupContact",
    "#createGroupPopupContact",
    "#reportPointPopupContact"
);

function getScrollY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return scrOfY;
}

function CategorySelectorOver() {
    if(typeof(ClearAll) != "undefined")
    {
        var elem = document.getElementById("CategorySelectorMenu");

        if(elem != null)
        {
            var k = getElementPosition(elem);

            $("#left_menu").css({
                "top": k.top + k.height,
                "left": k.left - 10
            });        
        
            $("#left_menu").show();
            return;
         }
    }
    
    CategorySelectorOut();
}

function CategorySelectorOut() {
    $("#left_menu").hide();
}

function getElementPosition(elem)
{    	
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;
	
    var l = 0;
    var t = 0;
	
    while (elem)
    {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }

    return {"left":l, "top":t, "width": w, "height":h};
}

function CategorySelectorClick() {

    if (typeof (ClearAll) != "undefined") {
        var d = $("#left_menu").css("display");
        if (d == 'none') {
            CategorySelectorOver();
        }
        else {
            CategorySelectorOut();
        }
    }
    else {
        location.href = "/home.aspx?mode=map";
    }
}

function CheckUserLogIn() {

    var url = "/Map.aspx/IsUserLogIn";

    var IsUserLogIn = $.ajax({
        type: "post",
        url: url,
        data:"{}",
        async: false
    }).responseText;

    return (IsUserLogIn == "true") ? true : false;
}

$("#createPointPopupContact").css("display")

Function.prototype.createDelegate = function(scope) {
    var fn = this;
    return function() {
        // Forward to the original function using 'scope' as 'this'.
        return fn.apply(scope, arguments);
    }
}

ModalPopup = function( popupId, closeElements,showElements, anonymVisible,contentUrl){
    this.popupId=null;
    this.anonymVisible=true;
    this.closeElements=new Array();
    this.showElements=new Array();
    this.contentUrl=null;
    this.init(popupId, closeElements,showElements,anonymVisible,contentUrl);
}

ModalPopup.prototype = {
    init: function(popupId, closeElements, showElements, anonymVisible, contentUrl) {

        this.popupId = popupId;
        this.closeElements = closeElements;
        this.showElements = showElements;

        if (anonymVisible != null) {
            this.anonymVisible = anonymVisible;
        }

        this.contentUrl = contentUrl;

        //if (this.popupId == "#createRoutePopupContact") { }

        $(this.popupId).draggable();

        for (i = 0; i < this.closeElements.length; i++) {
            $(this.closeElements[i]).click(function() {
                //disables popup only if it is enabled                
                $(popupId).fadeOut("slow");
            });
        }

        for (i = 0; i < this.showElements.length; i++) {
            $(this.showElements[i]).click(function() {
                //loads popup only if it is disabled
                if ($(popupId).css('display') == 'none') {

                    $(popupId).css({
                        'display': 'block'
                    }).animate({
                        opacity: 0.85
                    }, 500);
                }
            });
        }
    },

    show: function(latitude, longitude, id) {

        if (this.anonymVisible == true || this.checkCredentials() == true) {
            this.openEmpty(latitude, longitude, id);
        }
        else {
            login.show();
        }
    },



    openForEdit: function(itemId, type) {
        this.opened = true;
        if (this.anonymVisible == true || this.checkCredentials() == true) {
            var data = "id=" + itemId + '&type=' + type;

            var url = "/Map.aspx/GetMapItemDetails";

            $.ajax({
                type: "POST",
                async: false,
                url: url,
                data: data,
                contentType: "application/x-www-form-urlencoded",
                dataType: "html",
                success: this.responseHandler.createDelegate(this)
            });
        }
        else {

            login.show();
        }
    },

    openDialog: function(body) {
        this.responseHandler(body);
    },

    openEmpty: function(latitude, longitude, id) {

        var data = "url=" + this.contentUrl;

        if (latitude != null) {
            data = data + "&lat=" + latitude;
        }

        if (longitude != null) {
            data = data + "&lng=" + longitude;
        }
        if (id != null) {
            data = data + '&id=' + id;
        }

        if (typeof (GetFoundAddressMarker) != "undefined") {
            var addressMarker = GetFoundAddressMarker();
            if (addressMarker != null) {
                var p = new GLatLng(latitude, longitude);
                var distance = addressMarker.getLatLng().distanceFrom(p);
                if (distance < 50) {
                    data = data + "&FoundAddress=" + escape(addressString);
                }
            }
        }

        var url = "/Map.aspx/ReturnDialogContent";

        this.responseHandler($.ajax({
            type: "POST",
            async: false,
            url: url,
            data: data,
            contentType: "application/x-www-form-urlencoded",
            dataType: "html",
            async: false
        }).responseText);
    },

    checkCredentials: function() {

        return CheckUserLogIn();
    },

    responseHandler: function(response) {
        //alert(response);
        $(this.popupId).html(response);
        this.drawPoup();
    },

    drawPoup: function() {

        //request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;

        //SOME browsers dont support document.documentElement.clientWidth;
        if (windowWidth == null || windowWidth == 0)
            windowWidth = document.body.clientWidth;
        if (windowHeight == null || windowHeight == 0)
            windowHeight = document.body.clientHeight;

        var popupHeight = $(this.popupId).height();
        var popupWidth = $(this.popupId).width();

        var left = windowWidth == null || windowWidth == 0 ? 0 : windowWidth / 2 - popupWidth / 2;
        var top = windowHeight == null || windowHeight == 0 ? 0 : windowHeight / 2 - popupHeight / 2;

        if (windowHeight < popupHeight) {
            top = 22;
        }

        var scrollY = getScrollY();
        top = top + scrollY;

        //centering
        $(this.popupId).css({
            "position": "absolute",
            "top": top,
            "left": left
        });

        //loads popup only if it is disabled
        if ($(this.popupId).css('display') == 'none') {
            $(this.popupId).css({
                'display': 'block'
            }).animate({
                opacity: 0.85
            }, 500);
        }
    },

    hide: function(collect) {

        $(this.popupId).fadeOut("slow");

        if (collect != false) {
            if (typeof GarbegeCollectMarker != "undefined") {
                GarbegeCollectMarker();
            }
        }
    },

    get_popupId: function() {
        return this.popupId;
    },

    set_popupId: function(value) {
        if (this.popupId != value)
            this.popupId = value;
    },

    get_closeElements: function() {
        return this.closeElements;
    },

    set_closeElements: function(value) {
        if (this.closeElements != value)
            this.closeElements = value;
    },

    get_showElements: function() {
        return this.showElements;
    },

    set_showElements: function(value) {
        if (this.showElements != value)
            this.showElements = value;
    }
}

ModalPopup.descriptor = {
    properties: [   { name: 'showElements', type: Array },
                    { name: 'popupId', type: String },
                    { name: 'closeElements', type: Array }]
}

/**
 * Stratch gmap canvas height on window resize functionality
 */
function ShowDialogForCreateItem()
{
    selectItemTypeDialog.hide(false);

    var selectMapItem = $('#selectMapItem')[0];

    var lat=$(selectItemTypeDialog.popupId+" input[name='lat']").val();
    var lng = $(selectItemTypeDialog.popupId + " input[name='lng']").val();
    var type = selectMapItem.options[selectMapItem.selectedIndex].value;
    

    var dialog = ShowMapItemDialog(type);

    //if create route - show dialog for creating a route
    if (type == 1)
    {
        
        //clear marker without id
            $.each(markers, function(id, val) {
                if (val.id == "") {
                    removeMarker(val);
                    return;
                }
            })
        
        var points = new Array();
        
        points.push(map.getCenter());

        var route = createRoute(points);

        undoRoute = null;
        
        addRoute(route);
        showEditRouteDialog(route);
    }

    dialog.show(lat, lng);
}

function ShowRateDialog() {
    return rateDialog;
}

function ShowCommentDialog() {
    return commentDialog;
}

function ShowMapItemDialog(type)
{
  type = parseInt(type);

  switch (type) 
  {
        case 0:
            return createPointDialog;
            break;
            
        case 1:
            return createRouteDialog;
            break;
            
        case 2:
            return createEventDialog;
            break;
            
        case 3:
            return createGroup;
            break;

        case 4:
            return createLocationDialog;
            break;

        default:
            return createPointDialog;
    }
}

function isIE() {
    return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function ShowBuble(listShow) {
    var offset = $('#ads_box').position().left - 113;
    if (isIE())
        offset -= 0;
    $("#friendsonline").css("left", offset);    
    
}
function maxminsize() {

    var offValue = isIE() ? 62 : 58;
    var top = $('#fake_footer').position().top - offValue;    
    
    var height = 56;
    if ($('#friendsonlineList').css('display') == 'none') {
        top = $('#ads_box').position().top;        
        height = $('#ads_box').attr('offsetHeight');
        $('#friendsonlineList').show();
    }
    else {
        $('#friendsonlineList').hide();
    }
        
    $("#friendsonline").animate({
        top: top,        
        height: height
    }, 500);
    //$('#friendsTitle').attr('class', 'title');
}

$(window).resize(function() {
    var contentOffsetHeight = $("#height_prototype").attr('offsetHeight');

    var headerHeight = 0;
    $("#main_content h2, #main_content .block_top_big, #main_content .block_top_small, #main_content .block_bottom_big, #main_content .block_bottom_small, #main_content .navigation").each(function() {
        headerHeight += $(this).attr('offsetHeight');
    });    

    if (isIE()) contentOffsetHeight -= 4;    

    if ($("#ads_box").length != 0) {
        $("#ads_box").css("height", contentOffsetHeight + "px");               
        
        if ($("#map_for_you").length == 0) {
            $('#map_canvas').css("height", contentOffsetHeight - headerHeight - 4 + "px");
        }
        ShowBuble(false);
    }
});

//add listener for hook hotkeys

$(document).ready(function() {

    //chat drag (shef)
    $("#chat_window").draggable();


    $("#imgSelectbox").click(function() {
        $("#divSelectImitation").toggle();
    })

    selectCategoryDialog = new ModalPopup("#selectCategoryPopupDialog", [], [], true, "~/Views/PartialView/_CategorySelector.ascx");
    fogotPassword = new ModalPopup("#FogotPopupContact", [], [], true, "~/Views/PartialView/AccountMng/_FogotPassword.ascx");
    registerForm = new ModalPopup("#registerPopupContact", [], [], true, "~/Views/PartialView/AccountMng/_Register.ascx");
    profileForm = new ModalPopup("#profilePopupContact", [], [], false, "~/Views/PartialView/AccountMng/_Profile.ascx");
    selectItemTypeDialog = new ModalPopup("#selectItemTypePopupContact", [], [], false, "~/Views/PartialView/_MapItemTypeSelector.ascx");

    reportPoint = new ModalPopup("#reportPointPopupContact", [], [], true, "~/Views/PartialView/Point/_ReportPoint.ascx");
    createPointDialog = new ModalPopup("#createPointPopupContact", [], [], false, "~/Views/PartialView/Point/_CreatePoint.ascx");

    createLocationDialog = new ModalPopup("#createLocationDialog", [], [], false, "~/Views/PartialView/Location/_CreateLocation.ascx");

    createRouteDialog = new ModalPopup("#createRoutePopupContact", [], [], false, "~/Views/PartialView/Route/_CreateRoute.ascx");
    createEventDialog = new ModalPopup("#createEventPopupContact", [], [], false, "~/Views/PartialView/Event/_CreateEvent.ascx");
    createGroup = new ModalPopup("#createGroupPopupContact", [], [], false, "~/Views/PartialView/Group/_CreateGroup.ascx");
    sharePoint = new ModalPopup("#sharePointPopupContact", [], [], false, "~/Views/PartialView/Point/_SharePoint.ascx");
    downloadToMobile = new ModalPopup("#downloadPopupContact", [], [], false, "~/Views/PartialView/_DownloadToMobile.ascx");

    rateDialog = new ModalPopup("#ratePopupDialog", [], [], false, "~/Views/PartialView/_RateDialog.ascx");
    commentDialog = new ModalPopup("#commentsPopupDialog", [], [], true, "~/Views/PartialView/_CommentsDialog.ascx");

    loginAsk = new ModalPopup("#loginAskContact", [], [], true, "~/Views/PartialView/_HomeLoginAsk.ascx");    
    
    login = new LoginModal("loginRequired");

    //add event for quick filtering points    
    $("ul.categories li a").each(function(index, element) {

        $(element).click(function(e) {

            $("ul.categories li").attr("class", "");
            $(element).parent().attr("class", "selected");
            $("body").attr("class", $(element).parent().children('input').val().toLowerCase() );
            
            //clear all markers from map
            ClearAll()

            reloadMap()

            e.preventDefault();

        })
    });

    jQuery(document).bind('keydown', 'ctrl+s', function(evt) {

        //get ID of opened dialog
        var od = getOpenedDialogID()

        //fire event click
        $(od + " form button.button_imp").click()

        return false
    });

    $(window).trigger("resize");
});


    

/************************************************************************/
/* Return ID of Opened createion's dialog                                           */
/************************************************************************/
function getOpenedDialogID() {

    var opened_id = null
    
    $.each(create_popup_ids, function(n, val) 
    {
        if ( $(val).css("display") == 'block' )
        {
            opened_id = val
            return opened_id;
        }
    })

    return opened_id
}



function setAvatarValue(img, avatar)
{
    $("#inputSelectbox").val(avatar);
    $("#divSelectImitation").toggle();
    $("#imgCurrentImage").attr("src",img.src);
}

/************************************************************************/
/* Submit form handler                                                  */
/************************************************************************/
function SubmitForm(from, urlForRequest, AreaForUpade, dataInUrl)
{
    var sub = from.getElementsByTagName('input');
    var filePresent = false;
    query = new Array();

    for (var i = 0; i < from.length; ++i) 
    {
        if (from[i].type == "file")
        {
            filePresent = true;    
            break;
        }
    }
    for (var i = 0; i < from.length; ++i) 
    {            
        if (from[i].name) {

            if (from[i].type != 'radio' || from[i].checked != false) {            
                if (filePresent)
                    query.push(from[i].name + '=' + escape(from[i].value));
                else
                    query.push(from[i].name + '=' + escape(from[i].value));
            }
        }
    }

    query = query.join('&');

    if(filePresent)
        //makeRequest(urlForRequest, query, AreaForUpade, dataInUrl);
        makeFileRequest(urlForRequest, query, AreaForUpade, true, 'SelfAvatar');
    else
        makeRequest(urlForRequest, query, AreaForUpade, dataInUrl);
}

/************************************************************************/
/* Send Data from to Server
/************************************************************************/
function makeFileRequest(url, data, AreaForUpade, dataInUrl, filename ){


    if ( dataInUrl == true )
    {
        url=url+'?'+data;
        data="";
    }
    
    //data: data,
    $.ajaxFileUpload
    (
        {	        
	        url:url,
	        secureuri:false,
	        fileElementId:filename,
            dataType :"script",            
            success: function(response) {                
                $('#'+AreaForUpade).html(response);              
            },
            error: function (data, status, e)
            {
                alert(e);
            }
        }
    )
}

function processSuccess( data ) 
{
   alert( 'message = "' + data.message + '"' );
}
function makeRequest(url, data, AreaForUpade, dataInUrl ){

    if ( dataInUrl == true )
    {
        url=url+'?'+data;
        data="";
    }
    
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        contentType: "application/x-www-form-urlencoded",           
        dataType :"html",
        success: function(response) {
            $('#'+AreaForUpade).html(response);
        }
    });
}

LoginModal = function(popupId ){
    this.popupId=null;
    this.modalLogin=null;
    this.bachground=null;
    this.init(popupId);
    }

    LoginModal.prototype = {
        init: function(popupId) {
            this.popupId = popupId;
        },
        hide: function() {
            if (typeof (modalLogin) != "undefined") {
                $("#login").insertBefore($(".navigation_menu"));
                modalLogin.remove();
                bachground.fadeOut("slow");
            }
        },
        show: function() {
            modalLogin = $("<div />"); /*.load( $(element).attr('href') )*/
            modalLogin.attr('id', this.popupId);
            modalLogin.attr('class', "modal_popup");
            modalLogin.draggable();
            var close = $("<a>X</a>");
            close.attr("class", "close");
            this.hide.createDelegate()
            close.click(this.hide.createDelegate());

            close.appendTo(modalLogin);

            var headerText = $("<h4>Login</h4>");
            headerText.appendTo(modalLogin);

            var fieldset = $("<fieldset/>");
            fieldset.appendTo(modalLogin);

            $("#login").appendTo(fieldset);

            // Dmitry -  add cancel btn! 
            var cancelBtn = $("<button id=\"\"  type=\"button\" class=\"button_cancel\" onclick=\"login.hide();\">Cancel</button>")
            cancelBtn.click(function() {
                $("#login").insertBefore($(".navigation_menu"));
                modalLogin.remove();
                bachground.fadeOut("slow");
            });
            cancelBtn.appendTo(fieldset);

            //request data for centering
            var windowWidth = document.documentElement.clientWidth;
            var windowHeight = document.documentElement.clientHeight;

            var popupHeight = 162;
            var popupWidth = 363;



            //SOME browsers dont support document.documentElement.clientWidth;
            if (windowWidth == null || windowWidth == 0)
                windowWidth = document.body.clientWidth;
            if (windowHeight == null || windowHeight == 0)
                windowHeight = document.body.clientHeight;

            var left = windowWidth == null || windowWidth == 0 ? 0 : windowWidth / 2 - popupWidth / 2;
            var top = windowHeight == null || windowHeight == 0 ? 0 : windowHeight / 2 - popupHeight / 2;

            var scrollY = getScrollY();
            top = top + scrollY;

            //centering
            modalLogin.css({
                "position": "absolute",
                "top": top,
                "left": left
            });
            //loads popup only if it is disabled

            modalLogin.css({
                'display': 'block'
            }).animate({
                opacity: 0.85
            }, 500);

            bachground = $("<div />");
            bachground.attr("class", "backgroundPopup");
            bachground.css(
            {
                'display': 'block',
                "opacity": "0.7",
                'width': windowWidth,
                'height': (windowHeight + scrollY)
            });
            modalLogin.appendTo($("#header"));
            bachground.appendTo($("#header"));
        }
    }

/************************************************************************/
/* Common function                                                                     */
/************************************************************************/

function IsRouteDialodOpened() 
{
    return ( getOpenedDialogID() == "#createRoutePopupContact" )
}

function IsPointDialodOpened() 
{
    return ( getOpenedDialogID() == "#createPointPopupContact" )
}

function IsLocationDialodOpened() {
    return (getOpenedDialogID() == "#createLocationDialog")
}

function IsGroupDialodOpened() {
    return (getOpenedDialogID() == "#createGroupPopupContact")
}

function IsEventDialodOpened() {
    return (getOpenedDialogID() == "#createEventPopupContact")
}

function IsSelectCategoryDialogOpened() {
    return (getOpenedDialogID() == "#selectCategoryPopupDialog")
}

function showProfile(id) {
    profileForm.show(null, null, id);
}
function closeProfile() {
    profileForm.hide();
}
