///////////////////////////////////////////////////////////////////////////////
// Global vars

var gPopupModalShown = false;
var gReportFormShown = false;

///////////////////////////////////////////////////////////////////////////////

function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

function showBusyImage(){
    var newImg = document.createElement('img');
    newImg.setAttribute('src', live_site_busyImg);
    newImg.setAttribute('id',"jc_busyImg");
    $("jc_busyDiv").appendChild(newImg);
}

function removeBusyImage(){
    var t = $("jc_busyImg");
    if(t != null){
        t.parentNode.removeChild(t);
    }
}

function calcNumComment(){
    var comments = $("pc_comments").innnerHTML;
}

function addText(text, textarea){
	 var comment = $(textarea).value;
	 comment = comment + text;
	 $(textarea).value = comment;
}

function replaceText(text, textarea)
{
	// Attempt to create a text range (IE).
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		caretPos.select();
	}
	// Mozilla text range replace.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text + end;

		if (textarea.setSelectionRange)
		{
			textarea.focus();
			textarea.setSelectionRange(begin.length + text.length, begin.length + text.length);
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put it on the end.
	else
	{
		textarea.value += text;
		textarea.focus(textarea.value.length - 1);
	}
}

////////////////////////////////////////////////////////////////////////////////
function XMLHttpRequestObject(){
    var http_request = false;

   if (window.XMLHttpRequest) { // Mozilla, Safari,...
       http_request = new XMLHttpRequest();
   } else if (window.ActiveXObject) { // IE
        var msxmlhttp = new Array(
				'Msxml2.XMLHTTP.5.0',
				'Msxml2.XMLHTTP.4.0',
				'Msxml2.XMLHTTP.3.0',
				'Msxml2.XMLHTTP',
				'Microsoft.XMLHTTP');
        
        for (var i = 0; i < msxmlhttp.length; i++) {
			try {
				http_request = new ActiveXObject(msxmlhttp[i]);
			} catch (e) {
				http_request = null;
			}
		}
   }

   if (!http_request) {
       alert('Unfortunatelly you browser doesn\'t support this feature.');
       return false;
   }
   
   return http_request;
}

function submitTask(id, com, task, postData, responseFunc){

    var xmlhttp =  new XMLHttpRequestObject();
    var targetUrl = live_site;
            
    if(targetUrl.substr(-1, 1) == "/"){
        targetUrl += "index2.php";
    } else {
        targetUrl += "/index2.php";
    }

    xmlhttp.open('POST', targetUrl, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200){
                //alert(xmlhttp.responseText);
                if(responseFunc){
                    eval(responseFunc + "(xmlhttp.responseText);");
                    //alert("ok");
                } else {
                    if(xmlhttp.responseText){
                        var result = eval("(" + xmlhttp.responseText + ")");
                        switch(result.action){
                            case 'changeImg':
                                var img =  $(result.target);
                                img.setAttribute('src', result.imgsrc);
                                break;
                            case 'innerHTML':
                                var div =  $(result.target);
                                div.innerHTML = result.data;
                                break;
                            default:
                                break;
                        }
                        
                        clear_notification();
                    }
                    
                    hideBusyImage();
                }
            }else {
                // warning ajax fails
            }
        }
    }
    
    var xmlReq = ''; 
    xmlReq += '&option='+ com;
    xmlReq += '&no_html=1';
    xmlReq += '&task=ajax';
    xmlReq += '&xtask=' + task; 
    xmlReq += '&id=' + id;
    if(postData){
        xmlReq += postData;
    }

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(xmlReq);
}

function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                oldonload();
                func();
            }
        }
    }

function addComments(){
        var comment = $("jc_comment").value;
        var title   = $("jc_title").value;
        var id      = $("jc_contentid").value;
        var sid     = $("jc_sid").value;
        var pass    = 1;
        var rememberMe = true;
        
        changeOpac(100, "jc_busyDiv");
        
        if($("jc_rememberInfo") != null){
            rememberMe = $("jc_rememberInfo").checked;
        }
        
        // Store cookies 
        if($("jc_password") != null)
            pass = $("jc_password").value;

        if(comment.length > 0 && comment.length < 4000){
            comment = comment.replace(/&/g,"%26");
            title   = title.replace(/&/g,"%26");
            
            $("jc_title").disabled=true;
            $("jc_comment").disabled=true;
            $("jc_submit").disabled=true;
            $("jc_busyDiv").innerHTML = "";
            
            var xmlReq = '&jc_comment=' + comment + '&jc_password=' + pass;
            xmlReq += '&jc_title=' + title + '&jc_contentid=' + id; 
            xmlReq += '&jc_sid=' + sid; 
            xmlReq += '&jc_isajax=1';
            
            if($("jc_name") != null){
                $("jc_name").disabled=true;
                createCookie('jc_name', $("jc_name").value, 14);
                xmlReq += '&jc_name=' + $("jc_name").value;
            }
            
            if($("jc_email")){
                $("jc_email").disabled=true;
                createCookie('jc_email', $("jc_email").value, 14);
                xmlReq += '&jc_email=' + $("jc_email").value;
            }
                  
            if($("jc_website")){
                $("jc_website").disabled=true;
                createCookie('jc_website', $("jc_website").value, 14);
                xmlReq += '&jc_website=' + $("jc_website").value;
            }
            
            if(!rememberMe){
                eraseCookie("jc_name");
                eraseCookie("jc_email");
                eraseCookie("jc_website");
            }
            
            submitTask(0, 'com_jomcomment', 'add', xmlReq, 'jc_display_result')
            showBusyImage();
        }
        
        return false;
    }
    
    function display_notification(divName, theMessage){
        var message = "<div class=\"infolevel1\"></div>";
  	    message += "<div class=\"infolevel2\"></div>";
        message += "<div class=\"infolevel3\">" +theMessage+ "</div>";
        message += "<div class=\"infolevel2\"></div>";
        message += "<div class=\"infolevel1\"></div>";
              
        var d = $(divName);
        if(d != null){
            d.innerHTML = message;
        }
    }
    
    function jc_decode(str) {
        return unescape(str.replace(/\+/g, " "));
    }

	function jc_display_result(responseTxt) {
        responseTxt = responseTxt.substring(responseTxt.indexOf("{"));
	    var val = new Array(2);
        var result = eval("(" + responseTxt + ")");
    	var comment_div = $("jc_commentsDiv");

    	removeBusyImage();
    	
    	display_notification("jc_busyDiv", result.message);    
    	if(result.status != "ok"){
    	   
        } else {
            if(result.newComment.length > 0){
                result.newComment = jc_decode(result.newComment);
                if(orderBy){
            	   var oldCmt = $("newCd");
            	   if(oldCmt != null){
            	       oldCmt.setAttribute("id", "");
                   }
            	   var newCmt = document.createElement('div');
            	   newCmt.innerHTML = result.newComment;
                   changeStyleOpac(0,newCmt.style);
                   if(orderBy == "0"){
                        comment_div.insertBefore(newCmt,comment_div.firstChild);
                   } else {
            	       comment_div.appendChild(newCmt);
            	   }
            	   newCmt.setAttribute("id", "newCd");
            	   opacity("newCd", 0, 100, 500);        	   
            	   
                } else {
                    comment_div.innerHTML = result.newComment + comment_div.innerHTML;
                }
            }
            $("jc_comment").value = "";
        	$("jc_title").value = "";
        	
        	if(typeof(jc_commentArea) != 'undefined'){
        	   jc_commentArea.reset();
            }
            
            setTimeout("opacity(\"jc_busyDiv\", 100, 0,1000);", 3000);
    	}
    	
    	// change captcha image
    	if(document.jc_captchaImg != null){
            document.jc_captchaImg.src = result.captchaImg;
            if($("jc_sid") != null) $("jc_sid").value = result.sid;
        }
    	
        if($("jc_title") != null) $("jc_title").disabled=false;
        $("jc_comment").disabled=false;
        $("jc_submit").disabled=false;
        
        if($("jc_name") != null) $("jc_name").disabled=false;
        if($("jc_email")) $("jc_email").disabled=false;
        if($("jc_website")) $("jc_website").disabled=false;  
    }
    
    function jc_update_comment(responseText) {
        responseText = responseText.substring(responseText.indexOf("{"));
        var data = new Array(2);
        var result = eval("(" + responseText + ")");
        data[0] = result.status;
        data[1] = result.message;
        var comment_div = $("jc_commentsDiv");
        var oldComment = comment_div.innerHTML;
        
        // Should only add if the number of child is not the same
        if(data[1] != oldComment)comment_div.innerHTML = data[1];
         
        setTimeout("jc_update()",update_period);
    }
    
    function jc_update(){
        var id  = $("jc_contentid").value;

        /* Set up the request */
        var xmlhttp =  new XMLHttpRequestObject();
        var targetUrl = live_site;
        
        if(targetUrl.substr(-1, 1) == "/"){
            targetUrl += "index2.php";
        } else {
            targetUrl += "/index2.php";
        }
            
        xmlhttp.open('POST', targetUrl, true);
        
        /* The callback function */
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                if (xmlhttp.status == 200){
                    jc_update_comment(xmlhttp.responseText);
                }else {
                    //target.submit();
                }
            }
        }
        
        /* Send the POST request */
        var xmlReq = 'jc_task=update&no_html=1&jc_isajax=1&jc_contentid=' + id; 
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send(xmlReq);
    }

////////////////////////////////////////////////////////////////////////////////
function jc_reportCloseClick(){

    opacity("popupDiv", 100, 10, 400);
    setTimeout(function(){
        var body = document.getElementsByTagName('body')[0];
        var popDiv = $("popupDiv");
        var popCont = $("popupContainer");
        popCont.removeChild(popDiv);
        body.removeChild(popCont);
        gReportFormShown = false;
        
        }, 410);
    
}

/**
 *
 */ 
function jc_reportSendClick(){
     
}

////////////////////////////////////////////////////////////////////////////////
function jc_reportPost(postId){
    if(gReportFormShown)
        return false;
    
    var width = screen.width;
    var height = screen.height;
    
    var theBody = document.documentElement;	
	var scTop = parseInt(theBody.scrollTop,10);
	var scLeft = parseInt(theBody.scrollLeft,10);
    
    var body = document.getElementsByTagName('body')[0];
    var popcont = document.createElement('div');
	popcont.id = 'popupContainer';
	
	var popdiv = document.createElement('div');
	popdiv.id = 'popupDiv';
	
	popcont.style.display = "block";
	popcont.style.top = (scTop)+ 'px';
	popcont.style.left = (scLeft)+ 'px';
    popcont.style.width = (width-28) + "px";
	popcont.style.height = height + "px";
	popcont.style.position = "absolute";
	popdiv.innerHTML = '' +
	   '  <input name="textfield" type="text" style="width:100%;" size="55">'+
          '<strong>Reason to report:</strong><br>'+
          '<textarea name="textarea" cols="55" rows="4" style="width:100%;"></textarea>'+
          '<br/><br/>'+
          '<input type="submit" name="Submit" value="Submit"" onclick=\"jc_reportSendClick()\">'+
          '<input type="submit" name="Submit2" value="Close" onclick=\"jc_reportCloseClick()\">';
	
	var xPos = parseInt((width - 400)/2);
    var yPos = parseInt((height - 400)/2);
    
    var popdivId = $("popupDiv");
    
	
	popdiv.style.backgroundImage = "url(mambots/content/pcajaxcomment/templates/images/dialog_bg.gif)";
	popdiv.style.width= "400px"; 
	popdiv.style.padding = "15px";
	popdiv.style.display = "block";
	
	popdiv.style.top = ((screen.height-400)/2)+ 'px';
	popdiv.style.left = ((screen.width-400)/2)+ 'px';
	
    popdiv.style.position = "absolute";
    popdiv.style.background = "#FFFFCC";
    popdiv.style.border= "thick solid #CCCCCC";
    
    changeStyleOpac(0,popdiv.style);
    popcont.appendChild(popdiv);
    body.appendChild(popcont);
    opacity("popupDiv", 0, 100, 400);
    gReportFormShown = true;
	gPopupModalShown = true;

    //
    return false;
    /* Set up the request */
    var xmlhttp =  new XMLHttpRequestObject();
    var targetUrl = live_site;
    
    if(targetUrl.substr(-1, 1) == "/"){
        targetUrl += "index2.php";
    } else {
        targetUrl += "/index2.php";
    }
        
    xmlhttp.open('POST', targetUrl, true);
    
    /* The callback function */
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200){
                //jc_update_comment(xmlhttp.responseText);
                //alert(xmlhttp.responseText);
            }else {
                //target.submit();
            }
        }
    }
    
    /* Send the POST request */
    var xmlReq = 'jc_task=report&no_html=1&jc_isajax=1&jc_postId=' + postId; 
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(xmlReq);
}
    
////////////////////////////////////////////////////////////////////////////////
function jc_unpublishPost(postId){
    submitTask(postId, "com_jomcomment", "unpublish", null, "jc_unpublishPostResponse");
    $(postId).style.border = "medium solid #FF0000";
    opacity(postId,  100, 50, 200);
}

function jc_unpublishPostResponse(responseText){
}

function jc_commentAreaToggle(){
    if(typeof(jc_commentArea) != "undefined"){
        jc_commentArea.toggle();
        var img = $("toggleAreaImg");
        if(img != null){
            var imgSrc = img.src;
            if (jc_commentArea.el.offsetHeight > 0){
                imgSrc = imgSrc.replace("min.gif", "max.gif");
            } else{
                imgSrc = imgSrc.replace("max.gif", "min.gif");
            }
            img.src = imgSrc;
        }
    }
}

function jc_commentFormToggle(){
    if(typeof(jc_commentForm) != "undefined"){
        jc_commentForm.toggle();
        var img = $("toggleFormImg");
        if(img != null){
            var imgSrc = img.src;
            if (jc_commentForm.el.offsetHeight > 0){
                imgSrc = imgSrc.replace("min.gif", "max.gif");
            } else{
                imgSrc = imgSrc.replace("max.gif", "min.gif");
            }
            img.src = imgSrc;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = $(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

function changeStyleOpac(opacity, object) {
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

////////////////////////////////////////////////////////////////////////////////
function createCookie(name, value, days)
{
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return null;
}

function eraseCookie(name)
{
  createCookie(name, "", -1);
}

////////////////////////////////////////////////////////////////////////////////
addLoadEvent(function() {
    if((typeof update_period != "undefined")  && autoUpdate){
        setTimeout("jc_update()",update_period);
        
        // Fill up the name/email/website for unregistered user
        // with data stored in cookies, Need to be extra careful since emeil
        // protection bot will re-write our email address
        var _name = readCookie('jc_name');
        var _email =  readCookie('jc_email');
        var _website =  readCookie('jc_website');
        var _input;
        
        if(userEmail.length != 0){
            _email = userEmail;
        }
        
        if(_name != null){
            _input = $("jc_name"); 
            if(_input != null && _input.value.length == 0 && _name.length > 0){
                _input.value = _name;
            }   
        }
        
        _input = $("jc_email");
        if(_input != null && _input.type == "hidden"){
            _input.value = "none@noone.com";
        }
        
        if(_email != null){
            if(_input != null && _input.value.length == 0 && _email.length > 0){
               _input.value = _email;
            }
        }

        _input = $("jc_website"); 
        if(_input != null && _input.type == "hidden"){
            _input.value = "#";
        }
        if(_input != null && _website != null){
            if(_input.value.length == 0 && _website.length > 0){
                _input.value = _website;
            }   
        }
    }
});


function NewWindow(mypage,myname,w,h,scroll){
    LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
    TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
    settings =
    'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
    window.open(mypage,myname,settings)
}

// Surrounds the selected text with text1 and text2.
function encloseText(text1, text2, textarea)
{
	// Can a text range be created?
	if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
	{
		var caretPos = textarea.caretPos, temp_length = caretPos.text.length;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;

		if (temp_length == 0)
		{
			caretPos.moveStart("character", -text2.length);
			caretPos.moveEnd("character", -text2.length);
			caretPos.select();
		}
		else
			textarea.focus(caretPos);
	}
	// Mozilla text range wrap.
	else if (typeof(textarea.selectionStart) != "undefined")
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var newCursorPos = textarea.selectionStart;
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text1 + selection + text2 + end;

		if (textarea.setSelectionRange)
		{
			if (selection.length == 0)
				textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
			else
				textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
			textarea.focus();
		}
		textarea.scrollTop = scrollPos;
	}
	// Just put them on the end, then.
	else
	{
		textarea.value += text1 + text2;
		textarea.focus(textarea.value.length - 1);
	}
}
