﻿//Fix rendering bug, see https://extjs.com/forum/showthread.php?p=204817
Ext.form.TriggerField.override({
    afterRender: function() {
        Ext.form.TriggerField.superclass.afterRender.call(this);
        var y;
        if (Ext.isIE && !this.hideTrigger && this.el.getY() != (y = this.trigger.getY())) {
            this.el.position();
            this.el.setY(y);
        }
    }
});	

function userPickerInitWithTarget(textBoxControlID, userPickerID, onselect)
{
	var target=new Object();
	target.textBoxControlID=textBoxControlID;
	target.userPickerID=userPickerID;
	Ext.onReady(function() {
	    var queryUrl = "get/Searchuserprofiles/0/default.aspx"; //Todo: the last digit (0 or 1) means if only friends should be searched
	    var ds = new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({ url: queryUrl }),
	        reader: new Ext.data.XmlReader({
	            record: 'row',
	            totalRecords: 'totalCount',
	            id: 'user_id'
	        }, [
				'user_id', 'user_alias', 'user_first_name', 'user_last_name', 'up_status', 'user_profile_up_id', 'up_profile_album_pa_id'
		   ]),
	        remoteSort: true,
	        baseParams: {
	            dir: "ASC",
	            sort: "user_alias"
	        }

	    });
	
	    // Custom rendering Template
	    var resultTpl = new Ext.XTemplate(
		'<tpl for="."><div class="search-item">',
			'<img src="' + resourceUrl + 'photos/User/{user_id}/43x43-clip.jpg" style="width: 43px; height: 43px; padding: 4px 4px 0 4px" onmouseover="ProfileToolbox(this)" data-user_id="{user_id}"/>',
			'<a href="yourworld/{user_id}" class="profileLink" onmouseover="ProfileToolbox(this)" data-user_id="{user_id}">{user_alias}</a> ',
		'</div></tpl>');

	    var search = new Ext.form.ComboBox({
	        store: ds,
	        displayField: 'user_alias',
	        typeAhead: false,
	        loadingText: 'Söker...',
	        width: 145,
	        growMin: 145,
	        allowDomMove: false,
	        listWidth: 220,
	        shim: false,
	        emptyText: 'Skriv användarnamn',
	        grow: false,
	        pageSize: 0,
	        minChars: 2, //Minimum 2 characters to start searching
	        queryDelay: 100, //500 millisecond delay
	        selectOnFocus: true, //Autoselects text on focus
	        hideTrigger: true, // this will move the picker to the top if enabled = bug in extjs
	        forceSelection: true, //Restrict the selected value to one of the values in the list
	        tpl: resultTpl,
	        itemSelector: 'div.search-item',
	        applyTo: 'userSearchText' + target.userPickerID,
	        onSelect: function(record) {
	            if (onselect) {
	                onselect(record.data);
	                this.collapse();
	            }
	            else {
	                if (record.data != null) {
	                    document.getElementById(target.textBoxControlID).value = record.data.user_id;
	                    userpickerShowSelectedByUserID(record.data.user_id, target.userPickerID);
	                    userPickerShowImage = Ext.get('userPickerShowImage' + target.userPickerID, this);
	                    userPickerShowImage.on("click", function() { document.location = "yourworld/" + record.data.user_id; });

	                    this.collapse();
	                }
	            }
	        }
	    });
	});
return target;
}

function userpickerShowSelectedByUserID(userID, userPickerID)
{
    var userInfo = GetUserProfileInfo(userID, function(userInfo) {
	    document.getElementById('UserPickerMode' + userPickerID).className = "show";
	    document.getElementById('userPickerShowImage' + userPickerID).src = "Photos/User/" + userID + "/40x40.jpg";
		document.getElementById('userPickerLink' +userPickerID).href="yourworld/"+userInfo.userID;
		
		document.getElementById('userPickerAlias' +userPickerID).innerHTML=userInfo.UserAlias;
		document.getElementById('UserPickerMode' +userPickerID).className='show';
	});
}

/* Friend */
function addFriendAjax(friend_user_id)
  {
	var friend_category=getValue("friend_category");
	Iteam.Trex.Web.Site.Ajax.AddFriend(friend_user_id, friend_category, function(result)
		{
			if (result.error)
			{
				alert(result.error.Message); //Friend not added
			}
			 else
			{
				setValue("friend_category","");
			}
		});
}
  
  function removeFriendAjax(friend_id)
  { 
    document.body.style.cursor="cursor:wait";
	Iteam.Trex.Web.Site.Ajax.RemoveFriend(friend_id , function(result)
		{
		    document.body.style.cursor="";
			if (result.error)
			{
				alert(result.error.Message); //Friend not removed
			}
			 else
			{
			 document.location=document.location;
			}
		});
  }
	  
var addFriend = function(){
    var dialog, friend_user_id;
    
    return {
        init : function(){},
        showDialog : function(friend_user_id){
			addFriend.friend_user_id=friend_user_id;
            if(!dialog){ 
                dialog = new Ext.Window({ applyTo: "friend_dialog",
                    modal:true,
                    width:260,
                    height:130,
                    shadow:true,
                    buttons: [{
                        text: 'Ja',
                        handler: function() {
                            addFriendAjax(addFriend.friend_user_id);
                            dialog.hide();
                        }
                    }, {
                        text: 'Nej',
                        handler: function() {
                            dialog.hide();
                        }
                    }],
                    keys: [{key: 27, fn: function() { alertDlg.hide(); }}]                    
                });
            }
            
            dialog.on("show", function()
            {
               hideFlashObjects();
            });
            
            dialog.on("hide", function()
            {
               showFlashObjects();
            });
             
            dialog.show();
        }
    };
}();

/* Flirt */
function addFlirtAjax(flirt_user_id)
  {
	var flirt_category=getValue("flirt_category");
	Iteam.Trex.Web.Site.Ajax.AddFlirt(flirt_user_id, flirt_category, function(result)
		{
			if (result.error)
			{
				alert(result.error.Message); //Flirt not added
			}
			 else
			{
			    document.location = document.location;
			    setValue("flirt_category", "");
			}
		});
  }
  function removeFlirtAjax(flirt_id)
  {
    document.body.style.cursor="cursor:wait";
	Iteam.Trex.Web.Site.Ajax.RemoveFlirt(flirt_id , function(result)
		{
		    document.body.style.cursor="";
			if (result.error)
			{
				alert(result.error.Message); //Flirt not removed
			}
			 else
			{
			    document.location=document.location;
			}
		});
  }
	  
var addFlirt = function(){
    var dialog, flirt_user_id;
    
    return {
        init : function(){},
        showDialog : function(flirt_user_id){
			addFlirt.flirt_user_id=flirt_user_id;
            if(!dialog){
                dialog = new Ext.Window({ applyTo: "flirt_dialog",
                    modal:true,
                    width:300,
                    height:180,
                    shadow:true,
                    buttons: [{text: 'Ja',
                        handler: function() {
                            addFlirtAjax(addFlirt.flirt_user_id);
                            dialog.hide();
                        }}, {
                        text: 'Nej', handler: function() { dialog.hide(); } 
                    }
                    ],
                    keys: [{key: 27, fn: function() { dialog.hide(); }}]                    
                });
            }
            
            dialog.on("show", function()
            {
               hideFlashObjects();
            });
            
            dialog.on("hide", function()
            {
               showFlashObjects();
            });
             
            dialog.show();
        }
    };
}();

var tagPhotoDialog = function(){
    var dialog;
    
    return {
        init : function(){},
        showDialog : function(source){
            if(!dialog){
                dialog = new Ext.Window({ 
                    applyTo: "phototagContent",
                    modal:false,
					width:320,
					height:400,
					shadow:true,
					minWidth:300,
					minHeight:200,
                    buttons: [{text: 'Close',handler: function(){dialog.hide();}}],
                    keys: [{key: 27,fn: function() {dialog.hide();}}]						
                });
            }
            dialog.on("show", function()
            {
                 hideFlashObjects();
            });
            
            dialog.on("hide", function()
            {
                 showFlashObjects();
            });
             
            dialog.show(source);
        }
    };
} ();

Ext.ux.PersistentTip = Ext.extend(Ext.ToolTip, {
    initComponent: function() {
        Ext.apply(this, {
            showDelay: 150,
            hideDelay: 100,
            autoHide: false
        });
        Ext.ux.PersistentTip.superclass.initComponent.call(this);
    },

    afterRender: function() {
        Ext.ux.PersistentTip.superclass.afterRender.call(this);
        this.el.on('mouseout', this.onTargetOut, this);
        this.el.on('mouseover', this.onElOver, this);
    },

    checkWithin: function(e) {
        if (this.el && e.within(this.el.dom, true)) {
            return true;
        }
        if (this.disabled || e.within(this.target.dom, true)) {
            return true;
        }
        return false;
    },

    onElOver: function(e) {
        if (this.checkWithin(e)) {
            this.clearTimer('hide');
        }
    },

    onTargetOver: function(e) {
        if (this.disabled || e.within(this.target.dom, true)) {
            return;
        }
        this.clearTimer('hide');
        this.targetXY = e.getXY();
        this.delayShow(e);
    },

    delayShow: function(e) {
        this.showTimer = this.doShow.defer(this.showDelay, this, [e]);
    },

    doShow: function(e) {
        var xy = e.getXY();
        var within = this.target.getRegion().contains({ left: xy[0], right: xy[0], top: xy[1], bottom: xy[1] });
        if (within) {
            if (window.activeToolbox)
                window.activeToolbox.hide();
                
            this.show();
                
            window.activeToolbox = this;
        }
    },

    onTargetOut: function(e) {
        if (this.checkWithin(e)) {
            this.clearTimer('hide');
        } else if (this.hideTimer) {
            this.hide();
        } else {
            this.delayHide();
        }
    }
});

Ext.reg('persistenttip', Ext.ux.PersistentTip);

function ProfileToolbox(element, profileId) {
    if (isActiveUser) {
        if (!element.initialized) {
            element.initialized = true;
            element.menu = new Ext.ux.PersistentTip({
                target: element,
                baseCls: 'toolbox',
                width: 300,
                mouseOffset: [10, -80],
                defaultAlign: 'bl-tr',
                border: false,
                trackMouse: false,
                floating: { shadow: false }
            });

            element.user_id = 0
                
            if (profileId)
                element.profile_id = profileId;
            else
                element.profile_id = element.getAttribute("data-profile_id") ? element.getAttribute("data-profile_id") : element.getAttribute("profile_id");

            //This means the link only contains user_id and not profile_id
            if (!element.profile_id && element.getAttribute("data-user_id")) 
            {
                element.profile_id = 0;
                element.user_id = element.getAttribute("data-user_id");
            }

            element.menu.on("show", function() {
                hideFlashObjects();
                if (Ext.get(element).getX() < 800)
                    Ext.get(element.menu.el).anchorTo(element, 'bl-tr');
                else
                    Ext.get(element.menu.el).anchorTo(element, 'br-tl');

            });


            element.menu.on("hide", function() {
                showFlashObjects();
            });

            element.menu.on("beforeshow", function(e) {

                if (typeof (Iteam) != "undefined") {
                    if (!element.menuLoaded) { // only ask AJAX once for info

                        element.style.cursor = "wait";
                        for (var i = 0; i < AjaxPro.queue.requests.length; i++) {
                            if (AjaxPro.queue.requests[i].method == "GetProfileToolboxInfo" || AjaxPro.queue.requests[i].method == "WaitForUpdates")
                                AjaxPro.queue.requests[i].abort();
                        }
                        Iteam.Trex.Web.Site.Ajax.GetProfileToolboxInfo(element.profile_id, element.user_id, function(result) {
                            if (result.error) {
                                //  alert(result.error.Message);
                            }
                            else {
                                element.menuLoaded = true;

                                var data = result.value;
                                var link = element.parentElement;

                                if (link && link.tagName != "A")
                                    link = link.parentElement;

                                var template = new Ext.Template(toolboxTemplate);

                                data.imgSrc = "src='" + resourceUrl + "Photos/User/" + data.user_id + "/60x60-clip.jpg'";

                                if (data.friend_id == 0) data.is_friend = "hidden";
                                if (data.friend_id != 0) data.is_not_friend = "hidden";

                                if (data.flirt_id == 0) data.is_flirt = "hidden";
                                if (data.flirt_id != 0) data.is_not_flirt = "hidden";

                                if (data.isCompany) {
                                    data.ageRegion = "notvisible";
                                    data.matchRegion = "notvisible";
                                    data.is_flirt = "hidden";
                                    data.is_not_flirt = "hidden";
                                    data.is_friend = "hidden";
                                    data.is_not_friend = "hidden";
                                }

                                if (data.hasPhotos)
                                    data.has_no_photos = "hidden";
                                else
                                    data.has_photos = "hidden";

                                if (data.isOnline) data.is_not_online = "hidden";
                                if (!data.isOnline) data.is_online = "hidden";

                                data.rightArrow = "hidden";

                                newHtml = template.applyTemplate(data);

                                element.menu.body.update(newHtml);
                                element.style.cursor = "";

                                element.manualShow = true;
                            }
                        });
                    }
                }
            });
        }

        if (!element.manualShow && !Ext.isIE) {
            if (element.menu) {
                element.manualShow = true;

                // open tooltip
                element.menu.targetXY = Ext.get(element).getXY();
                element.menu.show();
            }
        }
    }
}