/** Author: Tony McGuckin, IBM **/
var sURL=''
var idList='';
var currUser = '';

function togglePreview(moreLinkId, lessLinkId,moreLinkId2, lessLinkId2, panelId, className) {
	try{
		var more = document.getElementById(moreLinkId);
		var less = document.getElementById(lessLinkId);
		var panel = document.getElementById(panelId);
		
		if (more)			
			more.style.display = "inline"
		
		if (less)
			less.style.display = "none";
		
		var more = document.getElementById(moreLinkId2);
		var less = document.getElementById(lessLinkId2);

		if (more)			
			more.style.display = "inline";
			
		if (less)
			less.style.display = "none";
		
		if (panel)
			//panel.className = className;
		     (panel.className == "xspDisplayInline") ? panel.className = "xspDisplayNone" : panel.className = "xspDisplayInline";
		
	}catch(e){
		alert(e.message);
	}
	return(false);
}


/** PDF Generation **/

var underlay 

function createPDF(arg, id){
	ret = 'pdfOutput=' + arg.output	
	ret = ret + '&pdfLanguage=' + arg.language
	ret = ret + '&pdfConcept=' + arg.concept
	
	var mycheck=arg.mycheck
	
	for (i=0; i<mycheck.length; i++)
		ret = ret + '&pdfType' + arg.mycheck[i] + '=' +  arg.mycheck[i]
		
	url = '/' + arg.recDb + '/pdfCreate?openagent&id=' + arg.did + '&' +  ret + '&user=' + currUser
	
	dojo.query('input:checked', "view:_id1").forEach("item.checked = false;");
	idList="";

	getPDF(url)	
//	getPDF('/sweden/recipes.nsf/pdfCreate?openagent&id=CBF43755C86316B8C12575D600269226&' + ret )	
}

function createMemo(arg){
		
		sURL=arg.host+arg.cust+"/xspRejectCurrent?openAgent&company="+arg.xid+ "&addr=" + arg.Mail + "&wmail=" + arg.sendMail + "&body=" + encodeURIComponent(arg.Body)
		callAgentOpenNew(sURL,'ajaxCalls')
}

function createProductSheetPDF(url){
	//url = "http://www.item.no"
	ret = 'url=' + url
	url = '/sweden/recipes.nsf/pdfProductSheet?openagent&' + ret
	getPDF(url)	
}

function getPDF(url) {
	loading()
    //The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
    var xhrArgs = {
    	url: url,
    	handleAs: "text",
    	load: function(data) {

		closeLoading() ;
    	window.open(data);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    },
    error: function(error) {
	alert( "An unexpected error occurred: " + error);
	}
	}

	//Call the asynchronous xhrGet
	var deferred = dojo.xhrGet(xhrArgs);
}


/** Contact Generation **/

function createContact(arg,h,c){

	var obj = eval("(" + arg + ')');
	var sURL = h + c + "/xspCreateContact?openagent&" + JSON(obj)
	return sURL
}

function JSON(a1){t=[];for(x in a1)t.push(x+"="+encodeURI(a1[x]));return t.join("&");}

function getContact(url) {
	loading()
    //The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
    var xhrArgs = {
    	url: url,
    	handleAs: "text",
    	load: function(data) {
		closeLoading() ;
    	window.open(data);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
    },
    error: function(error) {
	alert( "An unexpected error occurred: " + error);
	}
	}

	//Call the asynchronous xhrGet
	var deferred = dojo.xhrGet(xhrArgs);
}


////////////////////////////////////////////////////////////////////////////////


function loading() {
//	underlay = new dijit.DialogUnderlay({'class': 'loading'}); 
//	if (underlay)
//		underlay.show();
}

function closeLoading() {
//	if (underlay)
//	underlay.hide();
}

var prefix;
var btn;
var srchFld;

function runSearch(obj, prefix){
	for (i=0;i<11;i++)
		obj = obj.replace(prefix,"")
		p=eval("("+obj+")");
	
/*	
	alert(obj)
	alert(p.fldRecName)
	alert(p.fldIngrNr)
*/	
	
	var ret="";
	
	if (p.comp){
	ret = "(FIELD ResStatus CONTAINS Published)" 
	if (p.comp.length==1){
			if (p.comp[0]==1){
				ndx=2
				obj=dojo.query('[id$="comp2lbl"]')[0];
			}	
			else{
				ndx=1
				obj=dojo.query('[id$="comp1lbl"]')[0];
			}	
			ret += " AND (FIELD Firm CONTAINS NOT " + obj.innerHTML + ")"
	}
	}

	if (p.fldRecName!='') {
 	fld = p.fldRecName
	if (ret!="")	
 		ret = ret + " AND "
 		ret = ret + "(FIELD recName CONTAINS " + fld	 + "*)" 
	}

	if (p.fldIngrName!='') {
 	fld = p.fldIngrName
 	if (ret!="")	
 		ret = ret + " AND "
		ret = ret + "(FIELD IngrNames CONTAINS " + fld	 + "*)" 
	}

	if (p.fldIngrNr!='') {
 		fld = p.fldIngrNr
 		if (ret!="")	
 			ret = ret + " AND "
 			ret = ret + "(FIELD IngrCodes CONTAINS " + fld	 + "*)" 
	}

	if (p.Status)
	if (p.Status!='') {
 		fld = p.Status
 		if (ret!="")	
 			ret = ret + " AND "
 			ret = ret + "(FIELD ResStatus CONTAINS " + fld	 + "*)" 
	}
	
	if (p.Owner)
	if (p.Owner!='') {
 		fld = p.Owner
 		if (ret!="")	
 			ret = ret + " AND "
 			ret = ret + "( (FIELD xspCompany CONTAINS \"" + fld + "\") OR  (FIELD xspcreatedby CONTAINS \"" + fld + "\"))" 
	}

	if (p.keyHole)
	if (p.keyHole!='') {
 		fld = p.keyHole
 		if (ret!="")	
 			ret = ret + " AND "
 			ret = ret + "(FIELD ShowKeyhole=\"Y\")" 
	}


	tmp=""
	
	if (p.selectedTags)
	if (p.selectedTags!='') {
		tags = p.selectedTags.split(';')

		for (i=0; i<tags.length ;i++) {
			fld = tags[i]
			fld = fld.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
			if (fld!='' && fld!=' ')  {
 			if (ret!="")
 				if (tmp!="")	
 					tmp += " OR "	
 			tmp += "(FIELD xsptags CONTAINS \"" + fld	 + "\")"
 			}
 		}
	}


	if (tmp!="")
		ret += " AND (" + tmp + ")"


	tmp=""
	if (p.g1)
	if (p.g1!='') {
 		tmp += "(FIELD ShowBreadScaleTxt CONTAINS \"4\")" 
	}

	if (p.g2)
	if (p.g2!='') {
 			if (tmp!="")
 				tmp+=" OR "
 			tmp += "(FIELD ShowBreadScaleTxt CONTAINS \"3\")" 
	}

	if (p.g3)
	if (p.g3!='') {
 			if (tmp!="")
 				tmp+=" OR "
 			tmp += "(FIELD ShowBreadScaleTxt CONTAINS \"2\")" 
	}

	if (p.g4)
	if (p.g4!='') {
 			if (tmp!="")
 				tmp+=" OR "
 			tmp += "(FIELD ShowBreadScaleTxt CONTAINS \"1\")" 
	}


	if (tmp!="")
		ret+=" AND (" + tmp + ")"


obj=document.getElementById(srchFld)
obj.value=ret	
obj=document.getElementById(btn)
obj.click()

return ret

}


function returnTags(obj,prefix){
//	alert(prefix)
	for (i=0;i<3;i++)
	obj = obj.replace(prefix,"")
	
	p=eval("("+obj+")");

	var ret="";
	
	if (p.selectedTags)
		if (p.selectedTags!='') {
			ret=p.selectedTags
	}
	
	if (p.newTags)
		if (p.newTags!='') {
			ret+=";" + p.newTags
	}
	

obj=document.getElementById(srchFld)
obj.value=ret

return ret
}

function runSearch2(obj, prefix){

	for (i=0;i<11;i++)
		obj = obj.replace(prefix,"")
		p=eval("("+obj+")");
	
	var ret="";
	
	alert(p.fldRecName)
	
	if (p.comp){
	ret = "(FIELD RecType CONTAINS Published) AND (FIELD ResStatus CONTAINS Finished)" 
	if (p.comp.length==1){
			if (p.comp[0]==1)
				ndx=2
			else
				ndx=1	
			obj=document.getElementById(prefix+'comp' + ndx + 'lbl')
 			ret += " AND (FIELD Firm CONTAINS NOT " + obj.innerHTML + ")"
	}
	}

	if (p.fldRecName!='') {
 	fld = p.fldRecName
	if (ret!="")	
 		ret = ret + " AND "
 		ret = ret + "(FIELD recName CONTAINS " + fld	 + "*)" 
	}

	if (p.fldIngrName!='') {
 	fld = p.fldIngrName
 	if (ret!="")	
 		ret = ret + " AND "
		ret = ret + "(FIELD IngrNames CONTAINS " + fld	 + "*)" 
	}

	if (p.fldIngrNr!='') {
 		fld = p.fldIngrNr
 		if (ret!="")	
 			ret = ret + " AND "
 			ret = ret + "(FIELD IngrCodes CONTAINS " + fld	 + "*)" 
	}

	if (p.Status)
	if (p.Status!='') {
 		fld = p.Status
 		if (ret!="")	
 			ret = ret + " AND "
 			ret = ret + "(FIELD ResStatus CONTAINS " + fld	 + "*)" 
	}
	
	if (p.Owner)
	if (p.Owner!='') {
 		fld = p.Owner
 		if (ret!="")	
 			ret = ret + " AND "
 			ret = ret + "((FIELD RecOwner CONTAINS \"" + fld	 + "\") OR (FIELD RecFirm CONTAINS \"" + fld	 + "\"))" 
	}

	if (p.keyHole)
	if (p.keyHole!='') {
 		fld = p.keyHole
 		if (ret!="")	
 			ret = ret + " AND "
 			ret = ret + "(FIELD ShowKeyhole=\"Y\")" 
	}


	tmp=""
	
	if (p.selectedTags)
	if (p.selectedTags!='') {
		tags = p.selectedTags.split(';')

		for (i=0; i<tags.length ;i++) {
			fld = tags[i]
			fld = fld.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
			if (fld!='' && fld!=' ')  {
 			if (ret!="")
 				if (tmp!="")	
 					tmp += " OR "	
 			tmp += "(FIELD xsptags CONTAINS \"" + fld	 + "\")"
 			}
 		}
	}




return ret

}



function runPublicTagSearch(tag){
		//	alert(tag)
 			ret = "(FIELD xspTags CONTAINS " + tag + ")"
		//	alert(ret)
	if (tag!="")
		ret = ret + " AND (FIELD RecType CONTAINS Published) AND (FIELD ResStatus CONTAINS Finished)" 
	else
		ret = "(FIELD RecType CONTAINS Published) AND (FIELD ResStatus CONTAINS Finished)" 



obj=document.getElementById(srchFld)
obj.value=ret	
obj=document.getElementById(btn)
alert(btn)
obj.click()

return ret
	
}



var currFld;
var currFld2;
var currFld3;

/* Confirm dialog */
        function queryCallbackFn(arg) {
			if (arg==true){
				obj=document.getElementById(currFld);
				if (obj)
					obj.disabled=false
				obj=document.getElementById(currFld3);
				if (obj)
					obj.disabled=false
				obj=document.getElementById(currFld2);
				if (obj)
					obj.disabled=false
			}		
					
        }


        function deleteUser(arg) {
			if (arg==true) {
				load=true
				callAgent4(sURL,'ajaxCalls')
			}	
        }

        /* Utility function to raise a dialog asking the user a yes/no question. */
                function raiseQueryDialog(title, question, callbackFn) {
                var errorDialog = new dijit.Dialog({ id: 'queryDialog', title: title,  style: "width: 300px" });
                // When either button is pressed, kill the dialog and call the callbackFn.
                var commonCallback = function(mouseEvent) {
                errorDialog.hide();
                errorDialog.destroyRecursive();
                        if (mouseEvent.explicitOriginalTarget.id == 'yesButton') {
                                callbackFn(true);
                        } else {
                        		callbackFn(false);
                        }
                };
                var questionDiv = dojo.create('div', { innerHTML: question });
                var questionDiv2 = dojo.create('div', { innerHTML: '<br></br>' });
                var yesButton = new dijit.form.Button(
                            { label: 'Yes', id: 'yesButton', onClick: commonCallback });
                var noButton = new dijit.form.Button(
                            { label: 'No', id: 'noButton', onClick: commonCallback });

                errorDialog.containerNode.appendChild(questionDiv);
                errorDialog.containerNode.appendChild(questionDiv2);
                errorDialog.containerNode.appendChild(yesButton.domNode);
                errorDialog.containerNode.appendChild(noButton.domNode);

                errorDialog.show();
        }


		//function to check valid email address
		function isValidEmail(strEmail){
  			validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
  		//	strEmail = document.forms[0].email.value;

   			// search email text for regular exp matches
  			  if (strEmail.search(validRegExp) == -1) 
			   {
			      alert('A valid e-mail address is required.\nPlease amend and retry');
			      return false;
			    } 
			    return true; 
			}
		
        
        function validateContact(){
        	var ret=true
        	if (document.getElementById("FullName").value=="")
        		ret=false
        	else if (document.getElementById("FullName").value=="")
        		ret=false 	
        	else if (document.getElementById("Password").value=="")
        		ret=false 	
        //	else if (document.getElementById("EMailAddress").value=="")
        //		ret=false 	
        	else if	(isValidEmail(document.getElementById("EMailAddress").value)==false){
        		return false	
        	}	
        	else if (document.getElementById("MainPhone").value=="")
        		ret=false 	
        	else if (document.getElementById("CellPhone").value=="")
        		ret=false 	

        		
        	if (ret==false)
        		alert("All fields are mandatory. Email address must be a valid internet mail address") 	
        		
        		
        	return ret	
        		
        }
        
        function setFullName(fn1,ln1,full1){
        	fn=fn1=="" ? "FirstName" : fn1;
        	ln=ln1=="" ? "LastName" : ln1;
        	full=full1=="" ? "FullName" : full1;
        	
        	
        	f=document.getElementById(fn).value
        	l=document.getElementById(ln).value
        	document.getElementById(full).value= f + " " + l
        }
        
        
 // Dojo Dill
 function dialog_create(id, myTitle) {
var dialogWidget = dijit.byId(id);
if( dialogWidget ) dialogWidget.destroyRecursive(true);
dialogWidget = new dijit.Dialog( {title: myTitle }, dojo.byId(id)); 
var dialog = dojo.byId(id);
dialog.parentNode.removeChild(dialog); 
var form = document.forms[0]; form.appendChild(dialog); 
dialogWidget.startup(); 
}

function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function


// Access to Concepts

var publishClick=false;


function verifyContinue(txt){
	chb=dojo.query('[name$="Public"]')[0];
	if (chb)
		if (chb.checked==true) 
			if (confirm(txt)){
			chb.checked=false
			return true
		}else
		return false
	else
		return true;	
}

function publish(){
	chb=dojo.query('[name$="Public"]')[0];
	//fld=dojo.query('[name$="chooseFirm"]')[0];
	//link=dojo.query('[name$="searchLink"]')[0];
	//return(alert(chb))

	if (chb)
		if (chb.checked) {
			publishClick=true

		var readField = dojo.query('[name$="newRecOwner"]')[0];
		readField.value=''
	//	fld.disabled="disabled"
	//	link.style.display='none'
	}	
	else {

	//	fld.disabled=""	
	//	link.style.display='inline'
	}	
	
	//setDisplay()
}

function setDisplay(){
publish()
var readField = dojo.query('[name$="newRecOwner"]')[0];
tmp=readField.value	

//Rec reader field computed
//var readFieldComp = dojo.query('[id$="compNewRecOwner"]')[0];
//var readFieldComp2 = dojo.query('[id$="displayReaders"]')[0];
//var readFieldComp3 = dojo.query('[id$="displayAuthors"]')[0];
//var readFieldComp4 = dojo.query('[id$="displayCreatedBy"]')[0];

var readFieldComp = document.getElementById("compNewRecOwner");
var readFieldComp2 = document.getElementById("displayReaders");
var readFieldComp3 = document.getElementById("displayAuthors");
var readFieldComp4 = document.getElementById("displayCreatedBy");



var readFieldAuthor = dojo.query('[name$="AuthorAccess"]')[0];
var readFieldCreatedBy = dojo.query('[name$="createdBy"]')[0];

var list="";
if (tmp) 
	list=tmp.split("; ")


ret="";
ret2="";
for (i=0;i<list.length;i++) {
	if (list[i]!="") {
	ret+='<a href="#" onClick="removeComp(\'' + list[i] + '\')"><img src=\'iconRemoveColleague.gif\'>' +  list[i] + '</a><br>'
	ret2+=list[i]+ '<br>'
	}
}

readFieldComp.innerHTML=ret
readFieldComp2.innerHTML=ret2	
readFieldComp3.innerHTML=readFieldAuthor.value
readFieldComp4.innerHTML=readFieldCreatedBy.value

}

function addCompany(comp){
var tmp="";

//Rec reader field
var readField = dojo.query('[name$="newRecOwner"]')[0];
tmp=readField.value
tmp=replaceSubstring(tmp, comp, "");
tmp += "; " + comp;
list=tmp.split("; ")
ret=""
for (i=0;i<list.length;i++) {
	if (list[i]!=""){
		if (ret!="")
			ret += "; "
		ret+=list[i]
	}	
}
readField.value=ret;
setDisplay()

var readField = dojo.query('[name$="newRecOwner2"]')[0];
if (readField)
	readField.value=ret;
}

function removeComp(comp){
var tmp="";

//Rec reader field
var readField = dojo.query('[name$="newRecOwner"]')[0];
tmp=readField.value
tmp=replaceSubstring(tmp, comp, "");

list=tmp.split("; ")
ret=""
for (i=0;i<list.length;i++) {
	if (list[i]!=""){
		if (ret!="")
			ret += "; "
		ret+=list[i]
	}	 
}
readField.value=ret;
setDisplay()
}


