
function showMessage(msg){ 
	var htmlStr=msg; 
	$('#AjaxMsg').text(htmlStr);
    $('#AjaxMsg').fadeIn('slow').animate({opacity: 1.0}, 5000)
	.fadeOut('slow', function() {
      $(this).text('');
    });  
}  


function showMessageAny(id, msg){ 
	var htmlStr=msg; 
	var id=id; 
	$('#'+id).text(htmlStr);
    $('#'+id).fadeIn('slow').animate({opacity: 1.0}, 5000)
	.fadeOut('slow', function() {
      $(this).text('');
    });  
}  


// functions for deduping contacts 
function checkDivExists(fieldDescrip, fieldName, fieldValue, dupGoupId, dupIndivId, fieldValueDisplay){

        var divName1="newContact_"+dupGoupId;
        var divName2="newContactFieldWrapper_"+dupGoupId+"_"+fieldName;

        if ( $("#"+divName1+" #"+divName2+"").length ){
            //alert(divName1+" "+divName2+" already exists");
            //$("#errorWrapper_"+dupGoupId+"").html(""+fieldDescrip+" already exists.");
            showDupErrMessage(dupGoupId, fieldDescrip+" already exists.");
        }else{
          //alert(divName1+" "+divName2+" does not exist!");
//		 $.get('/contacts/contacts/dedupsetup', {'fieldDescrip':fieldDescrip, 'fieldName':fieldName, 'fieldValue':fieldValue, 'dupGoupId':dupGoupId, 'dupIndivId':dupIndivId}, function(data, textStatus) { 
		 $.get('/contacts/contacts/dedupsetup', {'fieldDescrip':fieldDescrip, 'fieldName':fieldName, 'fieldValue':fieldValue, 'dupGoupId':dupGoupId, 'dupIndivId':dupIndivId, 'fieldValueDisplay':fieldValueDisplay}, function(data, textStatus) { 
		 
		 	// append the divs
			 $('#newContact_'+dupGoupId).append(data); 
			 $('#newContactFieldWrapper_'+dupGoupId+'_'+fieldName).show('slow'); 
			 
			 // append the hidden form fields
			 var cleanedFieldValue=escape(fieldValue);
			 var hiddenField='<input type="hidden" name="'+fieldName+'" id="'+fieldName+'" value="'+fieldValue+'" />';
			 $('#dedupHiddenFormField_'+dupGoupId).append(hiddenField);
			 //$objResponse->assign('newContact_'.$dupGoupId, "style.width", 150);
			 $('#newContact_'+dupGoupId).attr('style', 'width:150');
			 
			 
			 }, 'html'
			 
			 );
        
			// scroll to the top of this contact dup group
			$('#dedupContactWrapper_'+dupGoupId).scrollTo(1000);
			
			 // inline edit of new contact fields, on hover turns into a text field
			 //inlineEditCustom();			
			 setTimeout("inlineEditCustom()", 1000); //needed a small delay

			 
			 
			
			 return false;
        }

    }
	
// for deleting an entire group of dups
function dedupDeleteProcess(divId, ids, fname, lname){


		 $.get('/contacts/contacts/dedupdelete', {'ids':ids}, function(data, textStatus) { 

		// show success msg:
		var fnameValueDisplay=rawurldecode(fname);
		var lnameValueDisplay=rawurldecode(lname);
//		$("#dedupContactWrapper_"+divId+"").html('<div id="SuccessWrapper"><div id="SuccessHdg">Dedupe complete for duplicate '+fnameValueDisplay+' '+lnameValueDisplay+' </div></div>');
		$("#dedupContactWrapper_"+divId+"").html('<div id="SuccessWrapper"><div id="SuccessHdg">Dedupe complete for duplicate "'+fnameValueDisplay+' '+lnameValueDisplay+'" </div></div>');
			
			 }, 'html'
			 
			 );
 			 
		// scroll to the top of this contact dup group
		$('#dedupContactWrapper_'+divId).scrollTo(1000);			  

}		
	
	
	
function dedupSetupRemove(fieldDescrip, fieldName, fieldValue, dupGoupId){
	
	$('#dedupForm_'+dupGoupId+' #'+fieldName).remove();
	$('#newContactFieldWrapper_'+dupGoupId+'_'+fieldName).remove();
	
	 // inline edit of new contact fields, on hover turns into a text field
	 //inlineEditCustom();			
	 setTimeout("inlineEditCustom()", 1000); //needed a small delay	

}
	
	
	
function showDupErrMessage(divId, msg){

	var htmlStr=msg;
	$("#errorMsgDupFade_"+divId+"").text(htmlStr);
	$("#errorMsgDupFade_"+divId+"").addClass("AjaxMsg");

	$("#errorMsgDupFade_"+divId+"").fadeIn("slow").animate({opacity: 1.0}, 1000);
	$("#errorMsgDupFade_"+divId+"").fadeOut("slow");
	return false; 
}

function dedupProcessAction(divId){
	
	$('#'+divId).ajaxForm(function() { 
	    alert("Thank you for your comment! "+divId); 
	}); 


}

function inlineEditCustom(){

	//alert('inlineEditCustom called');

    $(function(){
        $(".editable").inlineEdit({
            save: function(e, data) {

            // get contactid for replacing the form field
            var contactid=$(this).attr("contactid");
            var fieldname=$(this).attr("fieldname");
            //alert(data.value);

           $("#dedupHiddenFormField_"+contactid+" #"+fieldname+"").attr({ value: data.value });
           return;

            //return confirm("You are about to change your name to ""+ data.value +"\n\nAre you sure?");

            }
        });
    });


}

// use with jQuery Form
function validateJqForm(divId) { 

	//alert("Thank you for your comment! ");

    // fieldValue is a Form Plugin method that can be invoked to find the 
    // current value of a field 
    // 
    // To validate, we can capture the values of both the username and password 
    // fields and return true only if both evaluate to true 

    //var usernameValue = $('input[@name=fname]').fieldValue(); 
	var fnameValue=$("#dedupForm_"+divId+" #fname").val();
	var lnameValue=$("#dedupForm_"+divId+" #lname").val();
	
    // usernameValue and passwordValue are arrays but we can do simple 
    // "not" tests to see if the arrays are empty 
    if (!fnameValue || !lnameValue) { 
        alert('First name and Last name are required.'); 
		//showDupErrMessage(divId, 'First name and Last name are required.');
        return false; 
    } 
    alert('Both fields contain values.'); 
}



// use with jQuery Form
function validateJqFormNew(divId) { 

 	var fnameValue;
 	var lnameValue;
    //var usernameValue = $('input[@name=fname]').fieldValue(); 
	var fnameValue=$("#dedupForm_"+divId+" #fname").val();
	var lnameValue=$("#dedupForm_"+divId+" #lname").val();

    if (!fnameValue || !lnameValue) {
		//alert('First name and Last name are required.'); 
		showDupErrMessage(divId, 'First name and Last name are required.');
		return false;
	}else{
		
		// all good, submit the form via ajax
		$("#dedupForm_" + divId).submit();
		//alert('Both fields contain values.'); 
		
		// show success msg:
		var fnameValueDisplay=rawurldecode(fnameValue);
		var lnameValueDisplay=rawurldecode(lnameValue);
		$("#dedupContactWrapper_"+divId+"").html('<div id="SuccessWrapper"><div id="SuccessHdg">Dedupe complete for duplicate '+fnameValueDisplay+' '+lnameValueDisplay+' </div></div>');
		
	
	}
	
}

function rawurldecode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Ratheous
    // *     example 1: rawurldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin+van+Zonneveld!'
    // *     example 2: rawurldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: rawurldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    // *     example 4: rawurldecode('-22%97bc%2Fbc');
    // *     returns 4: '-22—bc/bc'
 
    var hash_map = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
 
    var replacer = function (search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
 
    // The hash_map is identical to the one in urlencode.
    hash_map["'"]   = '%27';
    hash_map['(']   = '%28';
    hash_map[')']   = '%29';
    hash_map['*']   = '%2A';
    hash_map['~']   = '%7E';
    hash_map['!']   = '%21';
 
 
    for (unicodeStr in hash_map) {
        hexEscStr = hash_map[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
 
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = ret.replace(/%([a-fA-F][0-9a-fA-F])/g, function (all, hex) {return String.fromCharCode('0x'+hex);}); // These Latin-B have the same values in Unicode, so we can convert them like this
    ret = decodeURIComponent(ret);
 
    return ret;
}

//--




/*
// alert box for deleting items
function callAlert(msg, url, id, name){
	
	var choice='<a href="javascript:;" onClick="doAlert(\'1\', \''+url+''+id+'\');">Yes</a> &nbsp; <a href="javascript:;" onClick="doAlert(\'0\', \''+url+'\');">No</a>';
	$("#alertInfo").html(msg+'<p>'+choice+'</p>');
	$('#alertBoxOverlay').fadeIn('slow');
	$('#alertBoxWrapper').css("display", "block");

}

function doAlert(choice, url){
	
	$('#alertBoxOverlay').fadeOut('slow');
	$('#alertBoxWrapper').css("display", "none");	
	if(choice==1){
		window.location=url;
	}
		
}
*/
//-- end alert box


// alert box for errors
function callAlertMsg(msg, url, id, name){
	
	var yes='&nbsp; <a href="javascript:;" onClick="doAlert(\'0\', \''+url+'\');">OK</a>';
	$("#confirm .message").html(msg);
	$("#confirm .buttons").html('<div class="confirmYes"><a href="javascript:;" onClick="doAlert(\'0\');">OK</a></div>');
	$('#alertBoxOverlay').fadeIn('slow');
	$('#confirm-container').css("display", "block");

}
//--

// new alert box ------------>
function callAlert(msg, url, id, name){
	
	//var choice='<a href="javascript:;" onClick="doAlert(\'1\', \''+url+''+id+'\');">Yes</a> &nbsp; <a href="javascript:;" onClick="doAlert(\'0\', \''+url+'\');">No</a>';
	var yes='<a href="javascript:;" onClick="doAlert(\'1\', \''+url+''+id+'\');">Yes</a>';
	var no='<a href="javascript:;" onClick="doAlert(\'0\');">No</a>';	
	$("#confirm .confirmYes").html(yes);	
	$("#confirm .confirmNo").html(no);	
	
	$("#confirm .message").html(msg);
	$('#alertBoxOverlay').fadeIn('slow');
	$('#confirm-container').css("display", "block");

}

function doAlert(choice, url){
	
	$('#alertBoxOverlay').fadeOut('slow');
	$('#confirm-container').css("display", "none");	
	if(choice==1){
		window.location=url;
	}
		
}


//--



// search functions called from the autosuggest
function searchPage(sendUrl){
	window.location=sendUrl;
}

// for contacts import
function findDuplicates(arr) {
        var i,
        len=arr.length,
        out=[],
        obj={};

        for (i=0;i<len;i++) {
                if (obj[arr[i]] != null) {
                        if (!obj[arr[i]]) {
                                out.push(arr[i]);
                                obj[arr[i]] = 1;
                        }
                } else {
                        obj[arr[i]] = 0;                        
                }
        }
        return out;
}






function GP_AdvOpenWindow(theURL,winName,features,popWidth,popHeight,winAlign,ignorelink,alwaysOnTop,autoCloseTime,borderless) { //v2.0
  var leftPos=0,topPos=0,autoCloseTimeoutHandle, ontopIntervalHandle, w = 480, h = 340;
  if (popWidth > 0) features += (features.length > 0 ? ',' : '') + 'width=' + popWidth;
  if (popHeight > 0) features += (features.length > 0 ? ',' : '') + 'height=' + popHeight;
  if (winAlign && winAlign != "" && popWidth > 0 && popHeight > 0) {
    if (document.all || document.layers || document.getElementById) {w = screen.availWidth; h = screen.availHeight;}
		if (winAlign.indexOf("center") != -1) {topPos = (h-popHeight)/2;leftPos = (w-popWidth)/2;}
		if (winAlign.indexOf("bottom") != -1) topPos = h-popHeight; if (winAlign.indexOf("right") != -1) leftPos = w-popWidth;
		if (winAlign.indexOf("left") != -1) leftPos = 0; if (winAlign.indexOf("top") != -1) topPos = 0;
    features += (features.length > 0 ? ',' : '') + 'top=' + topPos+',left='+leftPos;}
  if (document.all && borderless && borderless != "" && features.indexOf("fullscreen") != -1) features+=",fullscreen=1";
  if (window["popupWindow"] == null) window["popupWindow"] = new Array();
  var wp = popupWindow.length;
  popupWindow[wp] = window.open(theURL,winName,features);
  if (popupWindow[wp].opener == null) popupWindow[wp].opener = self;
  if (document.all || document.layers || document.getElementById) {
    if (borderless && borderless != "") {popupWindow[wp].resizeTo(popWidth,popHeight); popupWindow[wp].moveTo(leftPos, topPos);}
    if (alwaysOnTop && alwaysOnTop != "") {
    	ontopIntervalHandle = popupWindow[wp].setInterval("window.focus();", 50);
    	popupWindow[wp].document.body.onload = function() {window.setInterval("window.focus();", 50);}; }
    if (autoCloseTime && autoCloseTime > 0) {
    	popupWindow[wp].document.body.onbeforeunload = function() {
  			if (autoCloseTimeoutHandle) window.clearInterval(autoCloseTimeoutHandle);
    		window.onbeforeunload = null;	}
   		autoCloseTimeoutHandle = window.setTimeout("popupWindow["+wp+"].close()", autoCloseTime * 1000); }
  	window.onbeforeunload = function() {for (var i=0;i<popupWindow.length;i++) popupWindow[i].close();}; }
  document.MM_returnValue = (ignorelink && ignorelink != "") ? false : true;
}




