// P2N.Submission Component
// Copyright philly2night.com, 2008

P2N.Submission = {

    defaults: {
        'live': false,
        'liveOptions': false,
        'atm': false,
        'descr': false,
        'suggest': Array(),
        'img': {
            'index': 0,
            'previewID': false,
            'data': Array(),
            'maxItems': 0, // 0 - unlimited
            'count': 1,
            'url': 'frame_ajax_image.html'
        }
    },

    init: function() {

        var $d = P2N.Submission.defaults;

        // LiveText
        if ($d.live) {
            $d.live.each(function(live) {
                $j(live[0]).keyup(function() {
                    $j(live[1]).text($j(this).val());
                })
            })
        }

        // LiveOptions
        if ($d.liveOptions) {
            $d.liveOptions.each(function(options) {
                $j('input:checkbox', $j(options)[0]).click(function() {
                    var checked = $j(options[0] + ' input:checked');
                    var count = checked.length;
                    var list = "";
                    checked.each(function(i, n) {
                        var label = $j('label[@for="' + this.id + '"]').text();
                        if (options[2].withLinks) {
                            list += '<a href="#" onclick="return false">' + label + '</a>' + (i < count - 1 ? ', ' : '');
                        }
                        else {
                            list += label + (i < count - 1 ? ', ' : '');
                        }
                    });
                    $j(options[1]).html(list);

                })
            })
        }

        // Description
        if ($d.descr) {
            $j($d.descr.sourceID).keyup(function() {
                $j($d.descr.previewID).text($j(this).val());
                P2N.Submission.adjustRows(this);
            });
            $j($d.descr.sourceID).focus(function() {
                P2N.Submission.adjustRows(this);
            });
            if ($j($d.descr.sourceID).val().length > 0) {
                $j($d.descr.previewID).text($j($d.descr.sourceID).val());
            }
        }

        // Atmosphere
        if ($d.atm) {
            $j($d.atm.sourceID + ' input:checkbox').click(function() {
                var checked = $j($d.atm.sourceID + ' input:checked');
                var count = checked.length;
                if (count > $d.atm.maxItems) return false;
                var list = "";
                checked.each(function(i, n) {
                    list += '<a href="#" onclick="return false">' + $j(this).parent().text() + '</a>' + (i < count - 1 ? ', \n' : '');
                });
                $j($d.atm.previewID).html(list);
            });
        }
    },

    adjustRows: function(textarea) {
        var rows = textarea.rows;
        if (window.ie) {
            while ((textarea.scrollHeight > textarea.clientHeight) && (textarea.rows < 30)) {
                textarea.rows += 3;
            }
        } else {
            var strings = textarea.value.split("\n");
            var rowCount = 1;
            for (var i = 0; i < strings.length; i++) {
                if (strings[i].length > 75)
                    rowCount += Math.ceil(strings[i].length / 75);
            }
            rowCount += strings.length;
            if (rowCount > 4)
                textarea.rows = Math.min(rowCount, 30);
            else
                textarea.rows = 4;
        }
    },
    validate: function(eventControlID, eventHidCtrlID, placeControlID, placeHidCtrlID, radioEventControlID, radioPlaceControlID) {
        
        $('file-validator').hide();
        $('event-validator').hide();
        $('place-validator').hide();
 
        var isContainsFile = false;
        var col = $('uploadControlsContainer').getElementsByClassName('file-upload');
        for (var i = 0; i < col.length; i++) {
            var ctrl = col[i];
            if (!ctrl.value.blank()) {
                isContainsFile = true;
                break;
            }

        }


        if (!isContainsFile) {
            $('file-validator').show();
            return false;
        }

        if ($(radioEventControlID).checked) {
            if ($F(eventControlID).blank() || $F(eventHidCtrlID).blank()) {
                $('event-validator').show();
                return false;
            }

        }

        if ($(radioPlaceControlID).checked) {
            if ($F(placeControlID).blank() || $F(placeHidCtrlID).blank()) {
                $('place-validator').show();
                return false;
            }

        }

        return true;
    },

    toggleControls: function(controlToEnable) {
        if($('event-autosuggest') != null)
            $('event-autosuggest').hide();
        if($('place-autosuggest') != null)
            $('place-autosuggest').hide();
        if($('place-search-fieldset') != null)
            $('place-search-fieldset').hide();
        if($('event-validator') != null)
            $('event-validator').hide();
        if($('place-validator') != null)
            $('place-validator').hide();

        if (!controlToEnable.blank())
            $(controlToEnable).show();
    },

    uploadImage: function(row) {
        var img = P2N.Submission.defaults.img;
        var i = img.index;

        $j(row).after('<span id="show-action">&nbsp; <img src="img/i_action.gif" width="13" height="13" /></span>');

        $j.ajax({
            type: "GET",
            url: img.url,
            success: function(data) {
                img.data[i] = eval(data);
                P2N.Submission.defaults.img.index++;
                img.count++;

                if (img.count <= 0 || img.count == img.maxItems + 1) {
                    row.hide();
                }

                $j(img.previewID).show();

                var uploadedDiv = $j('.form-uploaded', row.parentNode)
                if (uploadedDiv.lenght) {
                    uploadedDiv.show();
                    if ($j('ul', uploadedDiv).length == 0) uploadedDiv.append('<ul></ul><br class="clear" />');

                    $j('ul', uploadedDiv).append('<li><img src="' + img.data[i][0] + '" alt="" /><a href="#" class="js-action-remove" onclick="P2N.Submission.removeImage(this); return false;">Remove</a></li>');

                }
                else {
                    $j(row.parentNode).before('<div class="form-field"><strong><a href="#" class="i-img">filename.jpg</a></strong> &nbsp; <a href="#" class="js-action-remove" onclick="P2N.Submission.removeImage(this); return false;">Remove</a></div>');
                    $j(img.previewID).html('<a href="#" title="Event name" onclick="return false;"><img src="' + img.data[i][1] + '" alt="Event name" title="Event name" />Enlarge image</a>');
                }

                $j('#show-action').remove();
                row.value = "";
            }
        });
    },

    removeImage: function(row) {
        var img = P2N.Submission.defaults.img;
        var i = img.index;
        img.count--;
        if (img.count <= 0 || img.count == img.maxItems) {
            $j(img.sourceID).show();
        }
        $j(row.parentNode).remove();
    },
    
    add: function(li) {
        var listTable = this.autoSuggest.recipients;
        if(listTable != undefined)
        {
            var elems = li.getElementsByTagName('div');
            
            var imgTd = document.createElement('td');
            imgTd.innerHTML = elems[0].innerHTML;
            
            var nameTd = document.createElement('td');
            nameTd.innerHTML = elems[1].innerHTML;
            
            var closeTd = document.createElement('td');
            closeTd.innerHTML = "<a href='#' class='i_remove' style='display:block;background-repeat:none;width:11px;height:11px;' title='Remove user from the list' onclick='P2N.Submission.remove(" + li.id + ");return false'></a>";
            
            var currentRow = document.createElement('tr');
            currentRow.id = li.id;
            currentRow.name = elems[1].innerHTML;
            currentRow.appendChild(imgTd);                
            currentRow.appendChild(nameTd);                
            currentRow.appendChild(closeTd);                
            
            listTable.tBodies[0].appendChild(currentRow);
        }
        
        
    },

    remove: function(id) {
        var listTable = this.autoSuggest.recipients;
        for(var i=0;i<listTable.tBodies[0].rows.length;i++) {
            if(listTable.tBodies[0].rows[i].id == id) {
                listTable.deleteRow(i);
            }
        }
    },

    exists: function(id){
        var listTable = this.autoSuggest.recipients;
        if(listTable != undefined){
            for(var i=0;i<listTable.tBodies[0].rows.length;i++) {
                if(listTable.tBodies[0].rows[i].id == id) {
                    return true;
                }
            }
        }
        return false;
    },
    
    redrawTable: function(hdnFieldID, hdnFieldName, listTable)
	{
	    var hdnFieldID = hdnFieldID.value;
	    var hdnFieldName = hdnFieldName.value;
        if(hdnFieldID != '' && hdnFieldName != '')
        {
            var recipientsIdsArray = hdnFieldID.substring(0,hdnFieldID.length - 1).split(',');
            var recipientsNamesArray =  hdnFieldName.substring(0,hdnFieldName.length - 1).split(',');
            
            for(var i=0;i<recipientsIdsArray.length;i++)
            {
                var imgTd = document.createElement('td');
                imgTd.innerHTML = "<div class='image'><img src='/Avatar.aspx?size=var5&memberID=" + recipientsIdsArray[i] + "'></div>";
            
                var nameTd = document.createElement('td');
                nameTd.innerHTML = "<div class='name'>" +  recipientsNamesArray[i] + "</div>";

                var closeTd = document.createElement('td');
                closeTd.innerHTML = "<a href='#' class='i_remove' style='display:block;background-repeat:none;width:11px;height:11px;' title='Remove user from the list' onclick='P2N.Submission.remove(" + recipientsIdsArray[i] + ");return false'></a>";

                var currentRow = document.createElement('tr');
                currentRow.id = recipientsIdsArray[i];
                currentRow.name = recipientsNamesArray[i];            

                currentRow.appendChild(imgTd);   
                currentRow.appendChild(nameTd);                
                currentRow.appendChild(closeTd);                
                
                listTable.tBodies[0].appendChild(currentRow);
            }
        }
	},
    
    autoSuggest: { // NEED to be fixed, need to mix options from init with some default ones

        init: function(fieldID, boxID, resultID, url, spinnerID, options) {
        
            this.recipients = $(options.recipients);
            
            P2N.Submission.defaults.suggest.push([fieldID, boxID, resultID, $(options.resultID)]);
            
            var $d = new Ajax.Autocompleter(fieldID, boxID, url, { paramName: 'value', minChars: 2, 'method': 'get', afterUpdateElement: this.getSelectionId, 'indicator': spinnerID });
            // IE fixing for arrow navigation and page scrolling
            if (Prototype.Browser.IE) {
                Event.observe($d.element, 'keydown', $d.onKeyPress.bindAsEventListener($d));
                $d.markPrevious = function() {
                    if ($d.index > 0) $d.index--
                    else $d.index = $d.entryCount - 1;
                    $d.getEntry($d.index).scrollIntoView(false);
                }
            }
        },

        getSelectionId: function(text, li) {
            var suggest = P2N.Submission.defaults.suggest;
            for (var i = 0; i < suggest.length; i++) {
                if (text.id == suggest[i][0]) break;
            }
            $(suggest[i][0]).value = li.down('.name').innerHTML.unescapeHTML();
            //$(suggest[i][2]).value = li.id;
            $(suggest[i][2]).value = '';
            if($(suggest[i][3]))
               $(suggest[i][3]).value = li.id;
            if(!P2N.Submission.exists(li.id))
                P2N.Submission.add(li);
        }
    },

    placeSearch: {
        init: function(resultFieldID, addressFieldID, zipFieldID, areaFieldID, cityID, searchURL, placeHiddenControlID, spinnerID) {
            this.resultFieldID = resultFieldID;
            this.addressFieldID = addressFieldID;
            this.zipFieldID = zipFieldID;
            this.areaFieldID = areaFieldID;
            this.cityID = cityID;
            this.searchURL = searchURL;
            this.placeHiddenControlID = placeHiddenControlID;
            this.spinnerID = spinnerID;
        },
        searchPlace: function() {
            this.showSpinner();

            new Ajax.Updater(this.resultFieldID, this.searchURL
				+ '?address=' + $F(this.addressFieldID)
				+ '&zip=' + $F(this.zipFieldID)
				+ '&cityID=' + this.cityID
				+ '&areaID=' + $F(this.areaFieldID)
				, { method: 'get', onSuccess: P2N.Submission.placeSearch.hideSpinner() });

        },
        showSpinner: function() {
            $(this.spinnerID).show();
        },
        hideSpinner: function() {
            $(this.spinnerID).hide();
        },
        selectPlace: function(placeNameLi) {
        if( $(this.placeHiddenControlID) != undefined)
            $(this.placeHiddenControlID).value = placeNameLi.down('div.name').innerHTML.unescapeHTML();
        }
    }


}

P2N.PictureFunctionality = {
    init: function(photoID) {
        $('photo-title').observe('mouseout', function(event) {
            $('photo-title').removeClassName('live-edit-hover');
        }
		);
        $('photo-title').observe('mouseover', function(event) {
            $('photo-title').addClassName('live-edit-hover');
        }
		);
        $('photo-title').observe('click', P2N.PictureFunctionality.toggleToEdit);
        $('btn-rename').observe('click', P2N.PictureFunctionality.renamePicture);
        $('btn-cancel').observe('click', P2N.PictureFunctionality.renamePictureCancel);
        $photoID = photoID;
    },

    renamePictureCancel: function() {
        $('photo-title-edit').hide();
        $('photo-title-container').show();
        $('error-save').hide();
    },

    renamePicture: function() {
        $('place-search-spinner').toggle();
        new Ajax.Request('/RenamePhoto.ashx?photoId=' + $photoID + '&photoName=' + $('f-photo_title').value, {
            onComplete: function(transport) {
                if (200 == transport.status) {
                    $('photo-title').innerHTML = $('f-photo_title').value;
                    $('picture-name-bottom').innerHTML = $('f-photo_title').value;
                    $('photo-title-edit').hide();
                    $('photo-title-container').show();
                    $('error-save').hide();
                }
                else {
                    $('error-save-text').innerHTML = transport.responseText;
                    $('error-save').show();
                }
                $('place-search-spinner').toggle();
            }
        });
    },

    toggleToEdit: function() {
        $('photo-title-container').hide();
        $('f-photo_title').value = unescape($('photo-title').innerHTML);
        $('photo-title-edit').show();
    },

    isPhotoTitleValid: function() {

        var myResult = {};
        myResult.isValid = true;
        $test = true;
        $('uploaded-photos').getElementsByClassName('fullsize title').each(function(ctrl, index) {
            ctrl.up('.form-row').down('.message').hide();

            if (ctrl.value.length > 128) {
                ctrl.up('.form-row').down('.error-save-text').innerHTML = "The title is too big.";
                ctrl.up('.form-row').down('.message').show();

                this.isValid = false;
            }
            if (ctrl.value != ctrl.value.unescapeHTML() || ctrl.value.gsub(/([&#@%\^])/, function(match) { }) != ctrl.value) {
                ctrl.up('.form-row').down('.error-save-text').innerHTML = "Incorrect characters.";
                ctrl.up('.form-row').down('.message').show();

                this.isValid = false;
            }

        }, myResult);

        return myResult.isValid;
    },

    tagThePicture: function(pictureID, memberID) {
        $('tag-picture-spinner').show();
        var url = '/TagPhoto.ashx?action=tag&pictureid=' + pictureID + '&memberid=' + memberID;
        new Ajax.Updater('panelWhoOnThePhoto', url);
        $('panel-tag-the-picture').hide();
        $('removePhotoDiv').show();
        $('panelWhoOnThePhoto').show();
        $('tag-picture-spinner').hide();
        return false;
    },
    unTagThePicture: function(pictureID, memberID) {
        $('tag-picture-spinner').show();
        var url = '/TagPhoto.ashx?action=untag&pictureid=' + pictureID + '&memberid=' + memberID;
        new Ajax.Updater('panelWhoOnThePhoto', url);

        $('removePhotoDiv').hide();
        $('panel-tag-the-picture').show();
        $('linkToTag').show();
        $('tag-picture-spinner').hide();
    }



}


P2N.Invite = {

    str: '',
    friendsDefault: [],
    friendsFilter: [],
    friendsInvited: [],

    cardContainer: new Template('<li>#{cardCheckbox}#{cardAvatarContainer}#{cardStatus}</li>'),
    cardCheckbox: new Template('<input type="checkbox" name="#{name}" id="#{id}" onclick="P2N.Invite.add()" />'),
    cardAvatarLabel: new Template('<label for="#{id}" class="avatar">#{cardAvatar}</label>'),
    cardAvatarSpan: new Template('<span class="avatar">#{cardAvatar}</span>'),
    cardAvatar: new Template('<span class="user">#{name}</span>'),
    cardStatus: new Template('<span class="#{className}">#{status}</span>'),
    cardRemove: new Template('<a href="#" class="i_remove" title="Remove user from the list" onclick="P2N.Invite.remove(#{id});return false">&nbsp;</a>'),

    init: function(init) {
        this.url = init.url;
        this.processURL = init.processURL;
        this.friendList = $(init.friendList);
        this.invitedList = $(init.invitedList);
        this.fieldFilter = $(init.fieldFilter);
        this.find('');
    },

    
    find: function(str) { // Find friends by part of the name
        var obj = this;
        this.str = str;

        if (str == '' || str == 'Find friends') { // Show defautlt list if string empty
            this.friendsFilter = this.friendsDefault;
            obj.draw(obj.friendsFilter);
        }
        else {
            P2N.addSpinner(obj.fieldFilter);
            new Ajax.Request(obj.url + '&str=' + str, {
                method: 'get',
                onSuccess: function(response) {
                    obj.friendsFilter = response.responseText.evalJSON();
                    obj.draw(obj.friendsFilter);
                    P2N.removeSpinner(obj.fieldFilter);
                    this.draw(obj.friendsFilter);
                }
                //			onFailure: function(){ alert('Something went wrong...') }
            });
        }

    },

    draw: function(list) {
        var obj = this;
        var friendList = '';
        
        if (list.length) {
            list.each(function(el) {
                if (el.type == 0) { // Sities2Night Friend
                    var i = el.name.toLowerCase().indexOf(obj.str.toLowerCase());
                    var cardAvatar = obj.cardAvatar.evaluate({

                        name: i >= 0 ?
								el.name.substring(0, i) +
								el.name.substring(i, i + obj.str.length).bold() +
								el.name.substring(i + obj.str.length, el.name.length) : el.name
                    });
                    var isAdded = 0;
                    if (obj.friendsInvited.length) {
                        obj.friendsInvited.each(function(elAdded) {
                            if (el.id == elAdded.id) isAdded = 1;
                        })
                    }

                    friendList += obj.cardContainer.evaluate({
                        cardCheckbox: el.status == 0 && !isAdded ? obj.cardCheckbox.evaluate({
                            name: 'invitecontacts',
                            id: 'invite-contact-' + el.id
                        }) : '',
                        cardAvatarContainer: el.status == 0 ? obj.cardAvatarLabel.evaluate({
                            id: 'invite-contact-' + el.id, cardAvatar: cardAvatar
                        }) : obj.cardAvatarSpan.evaluate({ cardAvatar: cardAvatar }),

                        cardStatus: el.status == 1 ? obj.cardStatus.evaluate({ // Attending
                            className: 'status-attending',
                            status: 'going to event'
                        }) : el.status == 2 || isAdded ? obj.cardStatus.evaluate({ // Added to list
                            className: 'status-invited',
                            status: 'added to list'
                        }) : el.status == 3 ? obj.cardStatus.evaluate({ // Already Invited
                            className: 'status-invited',
                            status: 'already invited'
                        }) : ''
                    })
                }
            })
        }
        this.friendList.update(friendList);
    },

    add: function() {
        $('error-notify').hide();
        var obj = this;
        var friendList = this.friendList.select('input');
        friendList.each(function(el) {
            if (el.checked) {
                obj.friendsFilter.each(function(friend) {
                    if (el.id == 'invite-contact-' + friend.id) {
                        friend.status = 2; // Added to the Invitation list
                        obj.friendsInvited.push(friend);
                        //							 alert(obj.friendsInvited.length);
                    }
                })
            }
        })
        this.find(this.str);

        var invitedList = '';

        this.friendsInvited.each(function(el) {
            var cardAvatar = obj.cardAvatar.evaluate({

                name: el.name
            })
            invitedList += obj.cardContainer.evaluate({
                cardAvatarContainer: obj.cardAvatarSpan.evaluate({ cardAvatar: cardAvatar }),
                cardStatus: obj.cardRemove.evaluate({ id: el.id })
            })
        })

        this.invitedList.previous('legend').down('.light').update('(' + this.friendsInvited.length + ')');
        this.invitedList.update(invitedList);
    },

    remove: function(id) {
        $('error-notify').hide();
        var index = -1;
        this.friendsInvited.each(function(el, i) {
            if (el.id == id) {
                el.status = 0;
                index = i;
                $break;
            }
        })
        this.friendsInvited.splice(index, 1);
        this.add();
    },

    cleanRecipients : function () {
        this.friendsInvited = [];
    },

    invite: function() {

        var invitedList = this.friendsInvited;
        $('error-notify').hide();
        if (invitedList.length == 0
            && $F('person-1-email').empty()
            && $F('person-2-email').empty()
            && $F('person-3-email').empty()
            && $F('person-4-email').empty()
            && $F('person-5-email').empty()) {
            $('error-notify').show();
            return false;
        }
        // Send invited list
        new Ajax.Request(this.processURL + '&inviteById=true', {
            postBody: 'invitedList=' + escape(invitedList.toJSON()) + '&' + Object.toQueryString($('emails-container').serialize(true)),
            onSuccess: function(response) {
            }
        });

        this.cleanRecipients();

        return true;

    },

    addRecipients: function() {

       
        this.friendsInvited.each(function(obj, index) {
             if(!P2N.Submission.exists(obj.id)){
                var li =  document.createElement('li');
                li.id = obj.id;
                li.innerHTML = "<div class='image'><img src='/Avatar.aspx?size=var5&memberID=" + obj.id + "'></div>" +
                "<div class='name'>" + obj.name + "</div>";
                P2N.Submission.add(li);
             }
        });

        //$$("textarea.fullsize")[0].value = myObject.addresses;

        this.cleanRecipients();
    }
    

}

P2N.MessagesFunctionality = {
    replyMessage: function(containerID, url) {
        $('pnMessageErrorSaving').hide();
        $('pnMessageRequired').hide();
        $('messageSent').hide();


        if ($F('txtMessage').empty()) {
            $('pnMessageRequired').show();
            return false;
        }
        
        re = new RegExp("\\x2B", "g");
        
        $('reply-spinner').show();
        new Ajax.Updater(containerID, url + '&action=reply', {
            postBody: 'replyMessage=' + encodeURIComponent($F('txtMessage')).replace(re, "%2B"),
            onSuccess: function(response) {
                $('reply-spinner').hide();
                $('messageSent').show();
            },
            onException: function(response) {
                $('reply-spinner').hide();
                $('pnMessageErrorSaving').show();
            }
        });

        $('txtMessage').value = "";





        return false;
    },

    replyClick: function(el) {
        el = $(el);
        if (el) {
            el.className = 'fullsize';
            el.rows = 10;
            $(el).next('p').show();
        }
    }
}

// Initialization
$j(document).ready(P2N.Submission.init);








