// Copyright (c) 2000 internet.com Corp.
// http://www.webreference.com/js/
// License is granted if and only if this entire
// copyright notice is included. By Tomer Shiran.


/*********************************************************************************************
 * Functions that help the Comment form to work
 */

/**
 * Check the comment form.
 */
function checkCommentForm() {
    
    // check each element
    var errors = new Object();
    
    var emailField = $('emailText');
    if (emailField) {
        
        var email = $F(emailField);
        
        if (!email) {
            errors.email = 'Please enter your email.';
        } else if (!emailCheck(email)) {
            errors.email = 'Invalid Email Address';
        }
    }
    
    var nameField = $('nameText');
    if (nameField) {
        var name = $F(nameField);
        if (!name) {
            errors.name = 'Please enter your name.';
        }
    }
    
    var comment = $F('commentText');
    
    if (!comment) {
        errors.comment = 'Whoops! Did you forget to comment?';
    }
    
    var previewCode = $F('previewCode');
    if (!previewCode && $F('theaction') == 's') {
        errors.id = 'Invalid submission, you must preview first.';
    }
    
    return errors;
}

/**
* Put rules associated with this form's actions
* in the commentRules object.
* An exception is the commentForm.commentSubmit() because 
* there is some funkiness with attaching this.

var commentRules = {
	
	//the contents of the prepareCommentForm()
	'#previewButton:click':function(el, ev) {
		 //console.log('%o', el);
		var action_val = $('commentForm').theaction;				
		action_val.value = 'p';
	 },
	
	'#submitButton:click':function(el,ev){
		//console.log('%o', el);
		//console.log('event %o', ev);				
		var action_val = $('commentForm').theaction;				
		action_val.value = 's';		
	},
	
	'#submitButton2:click':function(el, ev) {
		
		var action_val =$('commentForm').theaction;
		action_val.value = 's'; 
	},
	
	// var ilist = getElementsByTagNames('input',$('commentList'));
    
   '#commentList input:mouseover':function(el, ev) {
   		if (el){
   			//console.log('%o', el);
   			Element.addClassName(el, 'highlight');
   		}
    },
    
   '#commentList input:mouseout':function(el, ev) {
   		if (el){
   			//console.log('%o', el);
   			Element.removeClassName(el, 'highlight');
   		}
    },
     
    '#commentList input:click':function(el, ev) {
   		if (el){
   			//console.log('%o', el);
            $('commentID').value = el.id.substr(1);
   			
   		}
    }   

};*/
var commentFormRules = {
	
	//the contents of the prepareCommentForm()
	'#previewButton:click':function(el, ev) {
		 //console.log('%o', el);
		var action_val = $('commentForm').theaction;				
		action_val.value = 'p';
	 },
	
	'#submitButton:click':function(el,ev){
		//console.log('%o', el);
		//console.log('event %o', ev);				
		var action_val = $('commentForm').theaction;				
		action_val.value = 's';		
	},
	
	'#submitButton2:click':function(el, ev) {
		
		var action_val =$('commentForm').theaction;
		action_val.value = 's'; 
	} 

};

var commentDisplayRules = {
	     
   '#commentList input:mouseover':function(el, ev) {
   		if (el){
   			//console.log('%o', el);
   			Element.addClassName(el, 'highlight');
   		}
    },
    
   '#commentList input:mouseout':function(el, ev) {
   		if (el){
   			//console.log('%o', el);
   			Element.removeClassName(el, 'highlight');
   		}
    },
     
    '#commentList input:click':function(el, ev) {
   		if (el){
   			//console.log('%o', el);
            $('commentID').value = el.id.substr(1);
   			
   		}
    }   

};



var commentSubmit = function(element, event) {
	
	//console.log('commitSubmit');
	//debugger;
	//return false;
    clearFormErrors(); 
     
    if (!showFormErrors(checkCommentForm())) {  // check the errors and show them if they exist.        

    	// no errors were shown, so submit the form!        
        
    	
        // Make the AJAX call
        var url = baseurl + 'ajax/comment.php';
        var ajax = new Ajax.Request(url,
        {
            method:      'post',
            parameters:  Form.serialize('commentForm'),
            onSuccess:   commentPosted,
            onFailure:   commentFailed
        });
    }            
    return false;     
}

var commentPosted = function(oXML,json) {

    if (json.valid) {  // comment was really submitted.
        
        new Effect.Fade('commentPreview');
        
        Element.remove('previewedComment');
        
        Form.reset('commentForm');
        
        $('previewCode').value = '';
        
        new Effect.Fade('submitButton');
        
        // show the real comment above.
        commentRefresher();
        
    } else {  // they are previewing a comment.
        
        $('previewCode').value = json.previewCode;  
        
        var pc = $('previewedComment');
        
        var commentHTML = json.commenter+':<br />'+json.body; 
        
        if (!pc) {      
            
            new Insertion.Top('commentPreviewList','<li id="previewedComment" class="noDivider">'+commentHTML+'</li>');
        
            new Effect.BlindDown('commentPreview');
            
        } else {
            
            Element.update('previewedComment',commentHTML);
            
            new Effect.Highlight('commentPreview');
            
        }
        
        new Effect.Appear('submitButton');
        
    }
    return true;
}

var commentFailed = function(oXML,json) {
 	
    showFormErrors(json.errors);
    
    return true;
}
 
 
/**
* Used to add onload events
* Props to: Simon Willison
* See: http://simon.incutio.com/archive/2004/05/26/addLoadEvent
*/
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}	
	}
}

// use this wherever we want to add new rules
function addRules(obj) {
	
    var new_obj = {};
    [obj, rule_basket].each ( function (obj) {
        for (method in obj) { 
            new_obj[method] = obj[method]; 
        }
    });
    rule_basket = new_obj; 
}


/*********************************************************************************************
 * Functions that refresh the comment display
 */

function commentRefresher() { 
   
   cR = null; 
   checkForNewComments();
   cR = setTimeout('commentRefresher();',10000);
}

var checkForNewComments = function() {
	
    var commentsListItems = getElementsByTagNames('li',$('commentList'));
    var loadedComments = new Array;
    var item_id = $F('itemID');  // from the comment form
    var ministry_id = $F('minID');
    
    if (commentsListItems && commentsListItems.length > 0) {
        
        commentsListItems.each(function(oneli){
            //logit(oneli);
            if (oneli && oneli.id) {
                //logit(oneli.id);
                loadedComments.push(oneli.id.substr(3));  // get the number out of com123
            }
        });
    }
    
    /**
     * Make the AJAX call
     */
    var url = baseurl + 'ajax/loadComments.php';
    var ajax = new Ajax.Request(url,
    {
        method:      'post',
        parameters:  'loaded=' + loadedComments.toString() + '&id='+item_id+'&minid='+ministry_id,
        onSuccess:   displayComments
    });
    
}

var displayComments = function(oXML,json) {
 
    if (json.newComments) {
        
        if (json.newComments.length >= 1) {
            var noticeTag = $('noCommentNotice');
            if (noticeTag) {
                Element.remove(noticeTag);
            }
        }

        json.newComments.each(function(comment){
            
            var new_comment = '<li id="com'+comment.id+'"><div class="body">'+comment.body+'<br /><div class="postDate">posted on '+comment.created_on+' by ';
            
            if (comment.commenter_url) {
                new_comment = new_comment + '<a href="'+encodeURI(comment.commenter_url)+'">'+comment.commenter+'</a>';
            } else {
                new_comment = new_comment + comment.commenter;
            }
            
            new_comment = new_comment + '&nbsp;&nbsp;</div></div><div class="dash"></div></li>';
            
            new Insertion.Bottom('commentList',new_comment);
            new Effect.Highlight('com'+comment.id);
        });
    }
}

/*********************************************************************************************
 * Functions that help the report a Comment links to work
 */

var reportCommentFormSubmit = function() {
    var commentID = $F('commentID');
    if (commentID) {
        // turn off submit button
        Element.hide('r'+commentID);   
        Element.update('confirm'+commentID,'<a href="javascript: confirmOffensive(\'yes\')">Yes</a> or <a href="javascript: confirmOffensive(\'no\')">No</a> -  Are you sure this is offensive?');
    }
    return false;
}

function confirmOffensive(value) {
 
    var commentID = $F('commentID');
    
    if (value == 'yes') {

        /**
         * Make the AJAX call
         */
        var url = baseurl + 'ajax/flag.php';
        
        var ajax = new Ajax.Request(url,
        {
            method:      'post',
            parameters:  Form.serialize('reportCommentForm'),
            onSuccess:   commentReported
        });
        
    } else {
        Element.update('confirm'+commentID,'');
        Element.show('r'+commentID);
    } 
}

var commentReported = function(oXML,json) {
	
    if (json.reported) {
        var ricon = $('r'+json.reported);
        if (ricon) {
            
            Element.update('confirm'+json.reported,'reported');
            
        }
    }
}
   
function getElementsByTagNames(list,obj)
{
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++)
	{
		var tags = $A(obj.getElementsByTagName(tagNames[i]));
		tags.each(function(oneTag){
		    resultArray.push(oneTag);
		});
	}
	if (resultArray[0]) {
    	var testNode = resultArray[0];
    	if (testNode.sourceIndex)
    	{
    		resultArray.sort(function (a,b) {
    				return a.sourceIndex - b.sourceIndex;
    		});
    	}
    	else if (testNode.compareDocumentPosition)
    	{
    		resultArray.sort(function (a,b) {
    				return 3 - (a.compareDocumentPosition(b) & 6);
    		});
    	}
	}
	return resultArray;
}

function commentsDisplay(direction) {
    
    if ($('toggleCommentBlock') && $('commentBlock')) {
        if (direction == 'on') {
            Element.hide('toggleCommentBlock'); 
            Element.show('commentBlock');
        } else {
            Element.hide('commentBlock'); 
            Element.show('toggleCommentBlock');
        }
    }
}
/*********************************************************************************************
 * HELPER FUNCTIONS
 */

/**
 * Highlight every non-empty item of class "formError"
 */
function highlightFormErrors() {
    var errorElements = document.getElementsByClassName('formError');
    errorElements.each(function(oneElement) {
        if (oneElement && oneElement.innerHTML != '') {
            new Effect.Highlight(oneElement,{endcolor: '#CCCCCC'});
        }
    }); 
}

/**
 * Clear All items of class "formError"
 */
function clearFormErrors() {
    var errorElements = document.getElementsByClassName('formError');
    errorElements.each(function(oneElement) {
        if (oneElement && oneElement.innerHTML != '') {
            Element.update(oneElement,'');
        }
    }); 
}

/**
 * Given an object of the following type: fieldName=>ErrorMessage
 * Show the errors!
 */
function showFormErrors(errors) {
    var foundone = false;
    if (errors) {
        var t = '';
        for (var e in errors) {
            t = $(e+'Error');
            if (t) { 
                Element.update(t,errors[e]);
                foundone = true;
            }
        }        
        if (foundone) highlightFormErrors();
    } 
    return foundone;
}


/**
 * From: http://javascript.internet.com/forms/email-address-validation.html
 * Modified to fit into our system.
 */ 
function emailCheck (emailStr) {

    /* The following variable tells the rest of the function whether or not
    to verify that the address ends in a two-letter country or well-known
    TLD.  1 means check it, 0 means don't. */
    
    var checkTLD=1;
    
    /* The following is the list of known TLDs that an e-mail address must end with. */
    
    var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    
    /* The following pattern is used to check if the entered e-mail address
    fits the user@domain format.  It also is used to separate the username
    from the domain. */
    
    var emailPat=/^(.+)@(.+)$/;
    
    /* The following string represents the pattern for matching all special
    characters.  We don't want to allow special characters in the address. 
    These characters include ( ) < > @ , ; : \ " . [ ] */
    
    var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    
    /* The following string represents the range of characters allowed in a 
    username or domainname.  It really states which chars aren't allowed.*/
    
    var validChars="\[^\\s" + specialChars + "\]";
    
    /* The following pattern applies if the "user" is a quoted string (in
    which case, there are no rules about which characters are allowed
    and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
    is a legal e-mail address. */
    
    var quotedUser="(\"[^\"]*\")";
    
    /* The following pattern applies for domains that are IP addresses,
    rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
    e-mail address. NOTE: The square brackets are required. */
    
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    
    /* The following string represents an atom (basically a series of non-special characters.) */
    
    var atom=validChars + '+';
    
    /* The following string represents one word in the typical username.
    For example, in john.doe@somewhere.com, john and doe are words.
    Basically, a word is either an atom or quoted string. */
    
    var word="(" + atom + "|" + quotedUser + ")";
    
    // The following pattern describes the structure of the user
    
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    
    /* The following pattern describes the structure of a normal symbolic
    domain, as opposed to ipDomainPat, shown above. */
    
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    
    /* Finally, let's start trying to figure out if the supplied address is valid. */
    
    /* Begin with the coarse pattern to simply break up user@domain into
    different pieces that are easy to analyze. */
    
    var matchArray=emailStr.match(emailPat);
    
    if (matchArray==null) {
    
        /* Too many/few @'s or something; basically, this address doesn't
        even fit the general mould of a valid e-mail address. */
        
        //alert("Email address seems incorrect (check @ and .'s)");
        return false;
    }
    var user=matchArray[1];
    var domain=matchArray[2];
    
    // Start by checking that only basic ASCII characters are in the strings (0-127).
    
    for (i=0; i<user.length; i++) {
            if (user.charCodeAt(i)>127) {
            //alert("Ths username contains invalid characters.");
            return false;
       }
    }
    
    for (i=0; i<domain.length; i++) {
        if (domain.charCodeAt(i)>127) {
            //alert("Ths domain name contains invalid characters.");
            return false;
        }
    }
    
    // See if "user" is valid 
    
    if (user.match(userPat)==null) {
    
        // user is not valid
        //alert("The username doesn't seem to be valid.");
        return false;
    }
    
    /* if the e-mail address is at an IP address (as opposed to a symbolic
    host name) make sure the IP address is valid. */
    
    var IPArray=domain.match(ipDomainPat);
    if (IPArray!=null) {
    
        // this is an IP address
        
        for (var i=1;i<=4;i++) {
            if (IPArray[i]>255) {
                //alert("Destination IP address is invalid!");
                return false;
            }
        }
        return true;
    }
    
    // Domain is symbolic name.  Check if it's valid.
     
    var atomPat=new RegExp("^" + atom + "$");
    var domArr=domain.split(".");
    var len=domArr.length;
    for (i=0;i<len;i++) {
        if (domArr[i].search(atomPat)==-1) {
            //alert("The domain name does not seem to be valid.");
            return false;
        }
    }
    
    /* domain name seems valid, but now make sure that it ends in a
    known top-level domain (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding 
    the domain or country. */
    
    if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
        //alert("The address must end in a well-known domain or two letter " + "country.");
        return false;
    }
    
    // Make sure there's a host name preceding the domain.
    
    if (len<2) {
        //alert("This address is missing a hostname!");
        return false;
    }
    
    // If we've gotten this far, everything's valid!
    return true;
}
