var ArticleSectionEdit = Class.create({
    /**
     * Constructor
     *
     * @param string type
     */
    initialize: function(type) {
        this.type = type;
        this.zIndex = 0;
    },

    isIE6: function() {
        if(Prototype.Browser.IE && navigator.appVersion.match(/MSIE 6\.0/)) {
            return true;
        } else {
            return false;
        }
    },

    /**
     * Function that create an spesific observer for given section
     *
     * @param string section
     */
    addSectionObservers: function(section) {
        // Only add the observers if the article is editable
        if($$('div.'+this.type+'-'+section+'-editlink').size() > 0) {

            // Add edit link observer
            this.addEditLinkObserver(section);

            // Add cancel link observer
            this.addCancelLinkObserver(section);

            // Add remove item link observer
            this.addRemoveItemLinkObserver(section);

            // Add form observer
            this.addFormObserver(section);
        }
    },
    hideScrollBars: function() {
    	this.scrolloffset = document.viewport.getScrollOffsets();
    	
        document.getElementsByTagName('html').item(0).style.overflow = 'hidden';

        if(this.isIE6()) {
            window.scrollTo(0, 0);
        }
    },
    showScrollBars: function() {
    	

        if(this.isIE6()) {
            window.scrollTo(this.scrolloffset[0], this.scrolloffset[1]);
        }
        document.getElementsByTagName('html').item(0).style.overflow = 'auto';
    },
    /**
     * Function that add edit link observer by given section
     *
     * @param string section
     */
    addEditLinkObserver: function(section) {
        // Make the property type available for the observer functions
        var type = this.type;

        // Remove existing observer
        $$('div.'+type+'-'+section+'-editlink').first().childElements().first().stopObserving('click');

        // Add observer
        $$('div.'+type+'-'+section+'-editlink').first().childElements().first().observe('click', function(event) {
            // Stop click event
            event.stop();
            this.hideScrollBars();

            $$('div.'+type+'-'+section+'-edit').first().toggleClassName('hide');
        }.bindAsEventListener(this));



    },
    /**
     * Function that add cancel link observer by given section
     *
     * @param string section
     */
    addCancelLinkObserver: function(section) {
        // Make the property type available for the observer functions
        var type = this.type;
        // Add observers

        // Click on cancel link
        $$('div.'+type+'-'+section+'-cancellink').first().childElements().first().observe('click', function(event) {
            // Stop click event
            event.stop();
            this.showScrollBars();
            this.clearErrorMessage(section);

            $$('div.'+type+'-'+section+'-edit').first().toggleClassName('hide');

        }.bindAsEventListener(this));

        // Click on overlay
        $$('div.'+type+'-'+section+'-edit').first().childElements().first().observe('click', function(event) {
            this.showScrollBars();
            this.clearErrorMessage(section);

            $$('div.'+type+'-'+section+'-edit').first().toggleClassName('hide');
        }.bindAsEventListener(this));
    },
    /**
     * Function that add cancel link observer by given section
     *
     * @param string section
     */
     addRemoveItemLinkObserver: function(section) {
        // Make the property type available for the observer functions
        var type = this.type;
        var instance = this;

        // Add observer
        $$('a.removeitemlink').each(function(element) {
            if(element.descendantOf($$('div.'+type+'-'+section).first())) {
                element.observe('click', function(event) {
                    // Stop click event
                    event.stop();

                    // Append reposponse format
                    url = element.href + '&responseformat=text';

                    // Do ajax request instead
                    new Ajax.Request(url, {
                        method: 'get',
                        onComplete: function(transport) {
                            if(transport.responseText.length > 0) {
		                        $$('div.'+type+'-'+section).first().up('div',0).innerHTML = transport.responseText;

		                        // Re add observers
		                        instance.addCancelLinkObserver(section);
		                        instance.addRemoveItemLinkObserver(section);
		                        instance.addFormObserver(section);
		                    }
                        }
                    });
                });
            }
        });
     },
     
     clearErrorMessage: function(section) {
    	 var type = this.type;
    	 $$('div.'+type+'-'+section+'-edit').first().select('div.errormessage').first().update('');
     },
     
    /**
     * Function that add form observer by given section
     *
     * @param string section
     */
    addFormObserver: function(section) {
        // Make the property type available for the observer functions
        var type = this.type;
        var instance = this;
        var form = $$('div.'+type+'-'+section+'-edit').first().down('form');

        // Add observer
        form.observe('submit', function(event) {
            // Stop submit event
            event.stop();

            // Add response format input
            form.appendChild(new Element('input', { 'type': 'hidden', 'name': 'responseformat', 'value': 'html' }));

            // Change returnpage
            form.returnpage.value = '/submit-target-frame.php';

            // Add submit target iframe
            var objSubmitTargetFrame = new Element('iframe', { 'name': type+'-'+section+'-submit-target-frame', 'src': '/submit-target-frame.php' });
            objSubmitTargetFrame.setStyle({ 'display': 'none', 'position': 'absolute', 'top': '0px', 'left': '0px', 'width': '1px', 'height': '1px' });
            form.appendChild(objSubmitTargetFrame);

            // Add form target
            form.writeAttribute('target',type+'-'+section+'-submit-target-frame');

            // Submit form
            form.submit();

            // Check for complete submit every second
            new PeriodicalExecuter(function(pe) {
                if(objSubmitTargetFrame.contentWindow.document.title == 'section-data') {
                    // Stop periodical executer
                    pe.stop();

                    // Remove hide class on edit link
                    $$('div.'+type+'-'+section+'-editlink').first().removeClassName('hide');

                    // Re add updated html for given section
                    $$('div.'+type+'-'+section).first().up('div',0).innerHTML = objSubmitTargetFrame.contentWindow.document.body.innerHTML;
                    
                    
                    // Show scrollbars unless an error message is displayed
                    var errormessage = null;
                    var errorelement = $$('div.'+type+'-'+section+'-edit').first().select('div.errormessage').first();
                    if (errorelement.empty()) {
                    	this.showScrollBars();
                    } else {
                    	errormessage = section + '::' + errorelement.innerHTML;
                    }

                    var elementsToUpdate;
					var projectArticleId = null;
					
					switch(section) {
						case 'header':
							elementsToUpdate = ["company-contact"];
							break;
							
						case 'projectheader':
							elementsToUpdate = ["project-articlelist"];
							break;

						case 'image-1':
						case 'image-2':
						case 'image-3':
						case 'image-4':
							elementsToUpdate = ["project-articlelist","projectimages"];
							projectArticleId = $$('div.'+type+'-'+section+'-edit').first().down('form').down().readAttribute('value');
							break;
							
						case 'description':
						case 'specialproducts':
						case 'typesize':
							elementsToUpdate = ["profilecompleteness","profile-active"];
							break;
							
						case 'contact':
							elementsToUpdate = ["company-header","profilecompleteness","profile-active"];
							break;

						case 'awards':
						case 'recommendations':
						case 'references':
							elementsToUpdate = ["profilecompleteness"];
							break;
							
						default:
						    elementsToUpdate = [];
					}

					// Update additional elements if needed
					if (elementsToUpdate.size() > 0) {
					
						new Ajax.Request('/xmlhttprequest.php',
							{parameters: {'service': 		  'article.company.updateFields',
										  'responseformat':   'html',
										  'elementToUpdate':  elementsToUpdate.toJSON(),
										  'projectArticleId': projectArticleId,
										  'errormessage':	  errormessage},
							
							onSuccess: function(transport) {
								
								resultArray = transport.responseText.evalJSON();
								
								for (var key in resultArray) {
									$(key).update(resultArray[key]);
								}
							}
										  
						});
					}


					// Re add observers
                    instance.addEditLinkObserver(section);
                    instance.addCancelLinkObserver(section);
                    instance.addRemoveItemLinkObserver(section);
                    instance.addFormObserver(section);
                }
            }.bindAsEventListener(this), 1);
        }.bindAsEventListener(this));
    }
});


document.observe('dom:loaded', function(event) {
    var articleSectionEdit = new ArticleSectionEdit('company');
    articleSectionEdit.addSectionObservers('logo');
    articleSectionEdit.addSectionObservers('header');
    articleSectionEdit.addSectionObservers('description');
    articleSectionEdit.addSectionObservers('url');
    articleSectionEdit.addSectionObservers('employees');
    articleSectionEdit.addSectionObservers('awards');
    articleSectionEdit.addSectionObservers('recommendations');
    articleSectionEdit.addSectionObservers('references');
    articleSectionEdit.addSectionObservers('products');
    articleSectionEdit.addSectionObservers('specialproducts');
    articleSectionEdit.addSectionObservers('industries');
    articleSectionEdit.addSectionObservers('memberships');
    articleSectionEdit.addSectionObservers('contact');
    articleSectionEdit.addSectionObservers('typesize');

    var articleSectionEdit = new ArticleSectionEdit('project');
    articleSectionEdit.addSectionObservers('image-1');
    articleSectionEdit.addSectionObservers('image-2');
    articleSectionEdit.addSectionObservers('image-3');
    articleSectionEdit.addSectionObservers('image-4');
    articleSectionEdit.addSectionObservers('projectheader');
    articleSectionEdit.addSectionObservers('description');

    var articleSectionEdit = new ArticleSectionEdit('feedback');
    articleSectionEdit.addSectionObservers('feedbackform');
});




