//REF: mootools-window.js
//needed to call a special settimeout function because of jssec.js
var timeoutFunction;
if (window.restrictedSetTimeout)
    timeoutFunction = window.restrictedSetTimeout;
else
    timeoutFunction = window.setTimeout;
/*********************************************************
*HovPanel Functionality
*********************************************************/
var hovPanel;
var hovPanelBg = false;
var clickedToOpen = false;

function clearSrc()
{
    $('x-signinframe').src = 'javascript:false;';
    $('x-profilepicframe').src = 'javascript:false;';
}

function loadHovPanel()
{
    clickedToOpen = true;
}

function openHovPanel(panelId) {
    if( !clickedToOpen )
        return;
	hovPanel = $(panelId);
	if(!hovPanelBg) { hovPanelBg = $('x-hovpanel-bg'); }
	
	hovPanelBg.style.height = getDocumentHeight()+'px';
	hovPanelBg.style.display = 'block';
	function showBg() { hovPanelBg.style.display = 'block'; }
	timeoutFunction(showBg, 100);
	hovPanel.style.top = getCurrentYPos() + 60 + 'px';
	hovPanel.style.display = 'block';
}

function closeHovPanel(panelId) {
	if(panelId) { hovPanel = $(panelId); }
	if(!hovPanel) {
		hovPanel = parent.$(panelId);
    }
    if (!hovPanelBg) {
		hovPanelBg = parent.$('x-hovpanel-bg');
	}
	
	hovPanel.style.display = 'none';
	function hideBg() { hovPanelBg.style.display = 'none'; }
	timeoutFunction(hideBg, 100);
	hovPanelBg.style.display = 'none';
}

function getCurrentYPos() {
	return window.getScrollTop();
}

function getDocumentHeight() {
    return window.getScrollHeight();
}

function attachHovPanel(SrcId, panelId)
{
    var srcNode = $(SrcId);
    var targetNode = $(panelId+'-contents');
    targetNode.appendChild(srcNode);
}

/*********************************************************
*Force Signin/Join Functionality
*********************************************************/

function loadSignInFrame(source)
{
    clickedToOpen = true;
    $('x-signinframe').src = source + "&rand2=" + (Math.random() * 9999999);
}

function showSignIn()
{
    openHovPanel('x-hovpanel-signinjoin');
    $('x-signinframe').focus();
}

function submitPageForm(fromReg)
{
    if (!clickedToOpen)
        return;
       
    // 11/12/09 justin - i have no idea what this was for, but it was breaking registration on comment for pulse pages
    /*if( fromReg != null && fromReg == true )
    {
        $('registered').value = true;
    }*/
    
    var xangaForm = document.forms['pulse-form'];
    if( xangaForm.onsubmit != null )
        xangaForm.onsubmit();
    xangaForm.submit();
}

function notLoggedIn()
{
	closeHovPanel('x-hovpanel-chooseprofilepic');
	loadSignInFrame('/signinverify.aspx?loggedOut=parent.showSignIn();&loggedIn=parent.showProfilePic();&registered=parent.showProfilePic();&showsignin=True&rand=' + Math.random() * 9999999);
}

/*********************************************************
*Profile Pic Functionality
*********************************************************/
function showProfilePic()
{
    closeHovPanel('x-hovpanel-signinjoin');
    loadProfilePic();
}

function loadProfilePic()
{
    clickedToOpen = true;
	$('x-profilepicframe').src = "/profilepicchooser.aspx?rand=" + (Math.random() * 9999999);
}

function DisplayProfilePic(imageUrl, imageName, picName, width)
{
    var defaultTag = $('profilepic-default');
    var selectedTag = $('profilepic-selected');
    defaultTag.style.display='none';
    selectedTag.style.display='inline';

    var inputTag = $('selected-profilepic-url');
    inputTag.value = imageName;
    
    var imageTag = $('profilepic-img');
    imageTag.src = imageUrl;
    imageTag.alt = picName;
    
    var spanTag = $('profilepic-title');
    spanTag.innerHTML = picName;
}

function clearProfilePic()
{
    var defaultTag = $('profilepic-default');
    var selectedTag = $('profilepic-selected');
    defaultTag.style.display='block';
    selectedTag.style.display='none';

    //this is the only one that matters from an input point of view
    var inputTag = $('selected-profilepic-url');
    inputTag.value = "";
}

function popupProfilePic()
{
    var inputTag = $('profilepic-img');
    var wdw = window.open(inputTag.src,'_profull','width=200,height=220,resizable=1');
}

/*********************************************************
*Submit Button Functionality
*********************************************************/

function confirmSubmit(button)
{
    //hide button
    var xangasubmit = $('xangasubmit');
    xangasubmit.style.display='none';

    //show non-button text
    var blocksubmit = $('blocksubmit');
    blocksubmit.style.display='block';

    return true;
}
/*currently only valid for the new commentBox control!*/
function resetSubmit()
{
    var xangasubmit = $('xangasubmit');
    xangasubmit.style.display='block';

    var blocksubmit = $('blocksubmit');
    blocksubmit.style.display='none';
}

/*********************************************************
*Comment Reply Functionality
*********************************************************/
(function(){
    /*PUBLIC INTERFACES*/
    this.ReplyManager = {
        load: load,//(theInputId, theTargetId, theReplyInput)
        addReply: addReply, //(username,commentid)
        clear: clear //()
    }
    
    /*PRIVATE VARIABLES*/
    var inputId;
    var targetId;
    var replyInput;
    var text = false;
    /*PRIVATE METHODS*/
    
    function load(theInputId, theTargetId, theReplyInput)
    {
        inputId = theInputId;
        targetId = theTargetId;
        replyInput = theReplyInput;
        autoReplyTo();
    }
    function addReply(username,commentId)
    {
	    var OK = true;
	    var newText = "@" + username;
        var theTextArea = $(inputId);
            	    
	    if (theTextArea.value.match(text) != null && text!=newText )
	        OK = confirm('Pulses only allow one reply per comment.  Are you sure you want to switch users?');

        if (OK){
            if (theTextArea.value.match(text) != null)
                replaceText(text, newText);
            else
                insertText(newText + " - ");

            theTextArea.focus();    
            theTextArea.fireEvent('keyup', {}, 0);
            
            text = newText;
            $(targetId).value = newText;
            $(replyInput).value = commentId;
	    }
    }
    function clear()
    {
        var theTextArea = $(inputId);
    
        replaceText(text, "");
        
        theTextArea.focus();
        theTextArea.fireEvent('keyup', {}, 0);

        text = false;        
        $(targetId).value = "";
        $(replyInput).value = "";
    }
    function replaceText(theText, newText)
    {
        var theTextArea = $(inputId);
        var regEx = new RegExp(theText, 'g');
        theTextArea.value = theTextArea.value.replace(regEx, newText);
	    
    }
    function insertText(theText)
    {
	    var theTextArea = $(inputId);
        theTextArea.focus();
	    if (window.getSelection)//MOZILLA  & [OPERA & SAFARI]
	    {
            var start = theTextArea.selectionStart;
            var end = theTextArea.selectionEnd;
            theTextArea.value = theTextArea.value.substr(0, start) + theText + 
                theTextArea.value.substr(end, theTextArea.value.length); 
	    }
	    else if (document.selection)//IE
	    {
            document.selection.createRange().text = theText;
	    }
    }
    function parseQuery(key)
    {
        var query = location.search.substring(1);
        var pairs = query.split("&");
        for (var i = 0; i < pairs.length; i++)
        {
            var pair = pairs[i].split("=");
            if (pair[0] == key) return pair[1];
        }    
    }
    var autoReplyTo = function()
    {
        if (location.search.match("reply=")!=null)
        {
            window.addEvent('domready', function() {
                var id = parseQuery("reply");
                var target = "reply-" + id;
                var element = $(target);
                if (element)
                    element.onclick();
            });	
        }
    };
    
})();

/*********************************************************
*Character Limiting Functionality
*********************************************************/

function TextBox(id, characterLimit, charactersRemainingId) {
    var self = this;
    
    this.id = id;
    this.characterLimit = characterLimit;
    this.charactersRemainingId = charactersRemainingId;
    
    this.getElement = function() {
        return $(this.id);
    };
    
    this.getValue = function() {
        return self.getElement().value;
    };
    
    this.setValue = function(value) {
        this.getElement().value = TextBox.htmlDecode(value);
        this.updateCharacters();
    };
    
    this.isKeyPressAllowed = function(e) {
        if (!e) e = window.event;
        
        var charactersRemaining = self.getCharactersRemaining();
        self.setCharactersRemaining(charactersRemaining);
        
        var isAllowed = (self.getCharactersRemaining() > 0) || (e.keyCode != undefined && TextBox.ALLOWABLE_KEY_PRESSES[e.keyCode] != undefined);
        if (!isAllowed) {
            if (e.preventDefault) e.preventDefault();
        }
        return isAllowed;
    };
    
    this.updateCharacters = function() {
        var charactersRemaining = self.getCharactersRemaining();
        if (charactersRemaining < 0) {
            var truncatedBody = self.getValue().substring(0, self.characterLimit);
            self.setValue(truncatedBody);
            charactersRemaining = 0;
            
            alert('The Comment Box is full.  Your text has been trimmed to fit.');
        }
        self.setCharactersRemaining(charactersRemaining);
    };
    
    this.getCharactersRemaining = function() { return self.characterLimit - self.getValue().length; };
    
    this.setCharactersRemaining = function(charactersRemaining) { $(this.charactersRemainingId).innerHTML = charactersRemaining; };
    
    window.addEvent('domready', function() {
        var input = $(id);
        if (input){
            input.addEvent('keypress', self.isKeyPressAllowed);
            input.addEvent('change', function(event){
                self.isKeyPressAllowed(event);
                self.updateCharacters();
            });
            input.addEvent('keyup', self.updateCharacters);
        }
    }); 
}

TextBox.ALLOWABLE_KEY_PRESSES =
{
    '8':true, // delete
    '46':true, // backspace
    '35':true, '36':true, // end, home
    '37':true, '38':true, '39':true, '40':true // left, up, right, down
};

TextBox.htmlDecode = function(html) {
    html = html.replace(/&amp;/g, '&');
    html = html.replace(/&lt;/g, '<');
    html = html.replace(/&gt;/g, '>');
    html = html.replace(/&quot;/g, '"');
    html = html.replace(/&nbsp;/g, ' ');
    return html;
};



/*********************************************************
*Pulse Editor Light Box
*********************************************************/

var PulseEditor = {
    panelId: 'x-pulse-editor',
    textBox: new TextBox('x-item-content', 0, 'x-char-remaining'),
    
    reload: function() {
        window.location.reload();
    },
    
    onFailure: function() {
        window.location.href = 'http://www.xanga.com/sorry.aspx';
    },
    
    saveChanges: function() {
        var body = this.textBox.getValue();
        if (body.match(/\S/) != null) {
            this.prepareCallback(this.id, body, this.getPrivacy());
            if (this.id) {
                // editing
                this.updatePulse();
            }
            else {
                this.createPulse();
            }
            
            this.hide();
        }
        else alert(this.emptyMessage);
    },
    
    getRadioButton: function(privacy) {
        id = 'x-mod-opts-privacy-' + privacy;
        return $(id);
    },
    
    getPrivacy: function() {
        return this.getRadioButton('public').checked ? 1 : 0;
    },
    
    setPrivacy: function(privacy) {
        if (privacy == 1) this.getRadioButton('public').checked = true;
        else this.getRadioButton('private').checked = true;
    },
    
    showAddPanel: function(event) {
        var element = $(event.id)
        var pulseEditor = window.PulseEditor;
        pulseEditor.textBox.setValue('');
        pulseEditor.setPrivacy(1);
        delete pulseEditor.id;
        pulseEditor.toggleDisplayMode('add', 'edit');
        pulseEditor.show(element);
    },
    
    showEditPanel: function(event) {
        var element = $(event.id)
        var pulseEditor = window.PulseEditor;
        pulseEditor.id = pulseEditor.getPulseIdFromElement(element);
        var privacy = pulseEditor.getPrivacyFromElement(element);
        var body = $('itembody-' + pulseEditor.id).innerHTML.trim();
        pulseEditor.textBox.setValue(body);
        pulseEditor.setPrivacy(privacy);
        pulseEditor.toggleDisplayMode('edit', 'add');
        pulseEditor.show(element);
    },
    
    setOverlayDisplay: function(display) {
        $('x-hovpanel-bg').style.display = display;
    },
    
    clearOverlay: function() {
        PulseEditor.setOverlayDisplay('none');
    },
    
	getCurrentYPos: function() {
		if (document.body && document.body.scrollTop) { return document.body.scrollTop; }
		if (document.documentElement && document.documentElement.scrollTop) { return document.documentElement.scrollTop; }
		if (window.pageYOffset) { return window.pageYOffset; }
		return 0;
	},
	  
    show: function(element) {
        this.setOverlayDisplay('block');
        
        var x;
        var y;
        if (element) { y = PulseEditor.getCurrentYPos() + 120; }
        else { y = 120; }
        
        var editorPanel = $(this.panelId);
        editorPanel.style.top = y + 'px';
        editorPanel.style.display = 'block';
        setTimeout(function() { PulseEditor.textBox.getElement().focus(); }, 10);
    },
    
    hide: function() {
	 	var editorPanel = $(PulseEditor.panelId);
		editorPanel.style.display = 'none';
        setTimeout(PulseEditor.clearOverlay, 100);
    },
    
    toggleDisplayMode: function(showType, hideType) {
        this.setEditorDisplayMode(showType, 'block');
        this.setEditorDisplayMode(hideType, 'none');
    },
    
    setEditorDisplayMode : function(type, displayMode) {
        $('x-modsettings-title-' + type).style.display = displayMode;
    },
    
    htmlEncode: function(text) {
        text = text.replace(/&/g, '&amp;');
        text = text.replace(/</g, '&lt;');
        text = text.replace(/>/g, '&gt;');
        text = text.replace(/"/g, '&quot;');
        text = text.replace(/  /g, ' &nbsp;');
        return text;
    },

    getPulseIdFromElement: function(element) {
        var matches = element.id.match(/(\d+)$/);
        if (matches != null) return matches[1];
    },
    
    getPrivacyFromElement: function(element) {
        var matches = element.id.match(/1-\d+$/);
        if (matches != null) return 1;
        else return 0;
    },
    
    prepareCallback: function(id, body, privacy) {
        $(this.ids.id).value = id;
        $(this.ids.body).value = body;
        $(this.ids.privacy).value = privacy;
    }
    
};

window.addEvent('domready', function() {
    var button = $('x-pulseeditor-save');
    if (button)
        button.addEvent('click', function() { PulseEditor.saveChanges(); return false; });
}); 

