function lookupSiteInfo(){
    var siteUrl = getVal('siteUrl');
    if(siteUrl == undefined)
    {
        siteUrl = arguments[0];
    }

    if(isUrl(siteUrl))
    {
        document.getElementById('ajaxloader').innerHTML = "<img src='/images/ajax-loader_16x16.gif' border='0' />";
        partnerService.getSiteInfo(siteUrl, handleLookupSiteInfo);
    }
    else
    {
        document.getElementById('ajaxloader').innerHTML = "<img src='/images/icons/message_delete.png' alt='NOT OK' border='0' />";
    }
}

function isUrl(s){
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

function validateURL(){
    var url = arguments[0];
    url = trim(url);
    if(url != 0)
    {
        var j = new RegExp();
        j.compile("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");

        if (!j.test(url))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    return false
}

function trim(){
    var str = arguments[0];
    return str.replace(/^\s+|\s+$/g, '') ;
}

function stripWhiteSpace(){
    var str = arguments[0];
    str = trim(str);
    return str.replace(/\s+/g, '') ;
}

function checkNickname(){
    var nickname = getVal('nickname');
    if(nickname == undefined)
    {
        nickname = arguments[0];
    }
    partnerService.checkNickname(nickname, handleCheckNickname);
}

function handleCheckNickname(str){
    var sE = document.getElementById('checkNickname');
    if(str)
        sE.innerHTML = '<img src="/images/icons/message_accept.png" alt="OK" />';
    else
        sE.innerHTML = '<img src="/images/icons/message_delete.png" alt="NOT OK" />';
}

function checkPassword(){
    var pwd = getVal('password');
    
    if(pwd) {
    	jq$("#passwordCheck").load("/checkPasswordStrength.do?password="+pwd);
    }
}

function checkPasswordRetyped(){
    var pwd = jq$("#password").val();
    var pwdRetyped = jq$("#passwordRetyped").val();
    
    if(pwdRetyped != "")
    {
    	if(pwdRetyped == pwd)
    	{	
    		jq$("#passwordCheckRetypedNOK").hide();
    		jq$("#passwordCheckRetypedOK").css('display', 'inline');
    	}
    	else
    	{
    		jq$("#passwordCheckRetypedOK").hide();
    		jq$("#passwordCheckRetypedNOK").css('display', 'inline');
    	}
    }
    else
    {
    	jq$("#passwordCheckRetypedNOK").hide();
		jq$("#passwordCheckRetypedOK").hide();
    }
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    var top = Math.floor(( jq$(window).height() - this.height() ) / 2+jq$(window).scrollTop()) + "px";
    var left = Math.floor(( jq$(window).width() - this.width() ) / 2+jq$(window).scrollLeft()) + "px";
    this.css("top", top );
    this.css("left", left );
    return this;
}

function getVal(id){
    var v = document.getElementById(id);//$(id);//
    if(v != undefined && v != null)
    {
        return v.value;
    }
    else
    {
        return "";
    }
}

function uploadPreviewMedia(){
    new Ajax.PeriodicalUpdater(
            'status',
            '/status.jsp',
    {asynchronous:true, frequency:1, method:'get'});
    return false;
}

function popitupScrollbar()
{
    var url = arguments[0];
    var width = '600';
    var height = '800';

    if(arguments.length == 3)
    {
        width = arguments[1];
        height = arguments[2];
    }
    newwindow=window.open(url,'name','height='+height+',width='+width+',scrollbars=yes');
    if (window.focus) {newwindow.focus()}
    return false;
}

function get(id){return document.getElementById(id);}

function getSelectedCheckbox(buttonGroup) {
    var retArr = new Array();
    var lastElement = 0;
    if (buttonGroup[0]) {
        for (var i=0; i<buttonGroup.length; i++) {
            if (buttonGroup[i].checked) {
                retArr.length = lastElement;
                retArr[lastElement] = i;
                lastElement++;
            }
        }
    } else {
        if (buttonGroup.checked) {
            retArr.length = lastElement;
            retArr[lastElement] = 0;
        }
    }
    return retArr;
}

function getSelectedCheckboxValue(buttonGroup) {        
    var retArr = new Array();
    if(buttonGroup)
    {
        var selectedItems = getSelectedCheckbox(buttonGroup);
        if (selectedItems.length != 0) {
            retArr.length = selectedItems.length;
            for (var i=0; i<selectedItems.length; i++) {
                if (buttonGroup[selectedItems[i]]) {
                    retArr[i] = buttonGroup[selectedItems[i]].value;
                } else {
                    retArr[i] = buttonGroup.value;
                }
            }
        }
    }
    return retArr;
}

function uncheckAll(buttonGroup){
    if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
        for (var i=0; i<buttonGroup.length; i++)
        {
            buttonGroup[i].checked=false;
        }
    }
    else
    { // There is only one check box (it's not an array)
        buttonGroup.checked = false;
    }
    return false;
}

function checkAll(buttonGroup){
    if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
        for (var i=0; i<buttonGroup.length; i++)
        {
            buttonGroup[i].checked=true;
        }
    }
    else
    { // There is only one check box (it's not an array)
        buttonGroup.checked = true;
    }
    return false;
}

/**
 *
 * UTF-8 data encode / decode
 * http://www.webtoolkit.info/
 *
 **/
var Utf8 = {
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

function copyTo(value, id)
{
    document.getElementById(id).value = value;
}

String.prototype.replaceAll=function(s1, s2)
{
    return this.replace(new RegExp(s1,"gim"), s2);
}

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/g, '') ;
}

String.prototype.chop = function()
{
    return this.substr(this.length-2, 1);
}

String.prototype.endsWith = function(str) { return (this.match(str+"$")==str) };

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

function isset(  ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true

    var a=arguments; var l=a.length; var i=0;

    while ( i!=l ) {
        if (typeof(a[i])=='undefined' || a[i] == undefined || a[i] == '') {
            return false;
        } else {
            i++;
        }
    }

    return true;
}

if(typeof Class != "undefined"){	
	var CharCounter= Class.create({
		// field: input field to count chars
		// cntfield:element that displays num of chars left
		// maxlimit: take a wild guess...
	    initialize: function(field, cntField, maxLimit){
	    	this.field = $(field);
	    	this.cntField = $(cntField);
	    	this.maxLimit = maxLimit;
		    Event.observe(this.field, "keyup", this.update.bindAsEventListener(this), false);
	    },
	    update: function(){
	    	if (this.field.value.length > this.maxLimit) // if too long...trim it!
				this.field.value = this.field.value.substring(0, this.maxLimit);	
			else
				this.cntField.innerHTML = this.maxLimit - this.field.value.length; // otherwise, update  counter    	
	    }    
	});
}

function getDayDiff(dateA, dateB){
	var res = dateA-dateB;
	if(res < 0 ){
		res *= -1;
	}
	res = res / 1000 / 60 / 60 / 24;
	res = Math.ceil(res);	
	return res;
}


/* Takes X number of elements and flashes a highlight effect 
	 Deps: scriptaculous
*/
function flashHighlight(){
	for(i=0;i<arguments.length;i++){
		new Effect.Highlight(arguments[i], {startcolor: '#ffff99',endcolor: '#ffffff' });
	}
	return false;
}

function tsMultiSelect(selectEl, inputName) { 
	var option = selectEl.options[selectEl.selectedIndex];
	if(option.value=="")
	{
		return;
	} 
	var ul = selectEl.parentNode.getElementsByTagName('ul')[0]; 
	var choices = ul.getElementsByTagName('input'); 
	for (var i = 0; i < choices.length; i++)
	{ 
		if (choices[i].value == option.value) return;
	} 
		
	var li = document.createElement('li'); 
	var input = document.createElement('input'); 
	var text = document.createTextNode(option.firstChild.data); 
	input.type = 'hidden'; 
	input.value = option.value; 
	input.name = inputName;
	li.appendChild(input); 
	li.appendChild(text); 
	li.setAttribute('onclick', 'this.parentNode.removeChild(this);'); 
	ul.appendChild(li); 
}

function updateAllBoxes(formId, checkboxName, check){
	var form = $(formId);
	var boxes = Form.getInputs(form, 'checkbox', checkboxName);

	boxes.each(function(checkbox)
    {
		checkbox.checked = check;
    });
}

// Add hover behaviour for table>tbody>tr  (table with class="hoverRows")
jq$(document).ready(function() {
	jq$("table.hoverRows tbody tr").hover(
		function(){
			jq$(this).addClass("hoverRow");
		}, 
		function(){
			jq$(this).removeClass("hoverRow");
		}
	);
});

jq$(document).ready(function(){
	/* Using live() will make sure we add listeners to DOM loaded with AJAX */ 
	jq$("a:.partnerDetail").live("mouseover mouseout",function (e) 
	{
	  if (e.type == "mouseover")
	  {
		var partnerDetailDiv = jq$("#partnerDetail");
		partnerDetailDiv.show();
		partnerDetailDiv.position(
		{
			of:jq$(this),
			my: "left top",
			at: "left top",
			offset: "40",
			collision: "flip flip"
		});		
		jq$("#partnerDetail").load("/portletController.do?portletName=partnerDetailPortlet&partnerId="+jq$(this).attr("data-partner-id"));
	  }
	  else
	  {
		  jq$("#partnerDetail").hide();
	  }
	});
});
