var loc = 'app.php';

Blansys = {
	init:function() {
		this.loadClasses();
	},
	
	loadClasses:function(){
		ui 			= new UI();
	},
		
	drawHome:function(){
		document.location.href = "index.php";
	},
	
	drawWorkflow:function(){
		// ui.update("solutionsContent", "drawWorkflow", "Blansys");
		document.location.href = "index.php?link=Workflow";
	},
	
	drawProjectMang:function(){
		// ui.update("solutionsContent", "drawProjectMang", "Blansys");
		document.location.href = "index.php?link=ProjectMang";
	},
	
	drawColorMang:function(){
		// ui.update("solutionsContent", "drawColorMang", "Blansys");
		document.location.href = "index.php?link=ColorMang";
	},
	
	drawBookPlanning:function(){
		// ui.update("solutionsContent", "drawBookPlanning", "Blansys");
		document.location.href = "index.php?link=BookPlanning";
	},
	
	drawAdPortal:function(){
		// ui.update("solutionsContent", "drawAdPortal", "Blansys");
		document.location.href = "index.php?link=AdPortal";
	},
	
	drawInfrastructure:function(){
		// ui.update("solutionsContent", "drawInfrastructure", "Blansys");
		document.location.href = "index.php?link=Infra";
	},
	
	drawPhotobooks:function(){
		// ui.update("solutionsContent", "drawPhotobooks", "Blansys");
		document.location.href = "index.php?link=Photobooks";
	},
	
	drawSupport:function(){
		// ui.update("solutionsContent", "drawSupport", "Blansys");
		document.location.href = "index.php?link=Support";
	},
	
	drawSolutions:function(){
		document.location.href = "index.php?link=Solutions";
	},
	
	drawSolutions2:function(){
		document.location.href = "index.php?link=Solutions2";
	},
	
	drawClients:function(){
		document.location.href = "index.php?link=Clients";
	},
	
	drawNews:function(){
		document.location.href = "index.php?link=News";
	},
	
	drawDemoRequest:function(){
		/* ui.update("bodyContent", "drawDemos", "Blansys"); */
		document.location.href = "index.php?link=DemoRequest";
	},
	
	drawWebinarForm:function(){
		document.location.href = "index.php?link=WebinarForm";
	},
	
	drawSalesLead:function(){
		document.location.href = "index.php?link=SalesLead";
	},
	
	drawContact:function(){
		document.location.href = "index.php?link=Contact";
	},
	
	drawFreeTrial:function(){
		document.location.href = "index.php?link=FreeTrial";
	},
	
	// functions to redirect older pages
	
	mailToInfo:function(){
		var a = 'mailto:';
		var b = 'info';
		var c = '@';
		var d = 'blansys.com';
		var e = '?subject=BSI Information Inquiry';
		
		document.location.href = (a+b+c+d+e);
	},
	
	mailToJobs:function(){
		var a = 'mailto:';
		var b = 'jobs';
		var c = '@';
		var d = 'blansys.com';
		var e = '?subject=BSI Job Inquiry';
		
		document.location.href = (a+b+c+d+e);
	},
	
	mailToSales:function(){
		var a = 'mailto:';
		var b = 'sales';
		var c = '@';
		var d = 'blansys.com';
		var e = '?subject=BSI Sales Inquiry';
		
		document.location.href = (a+b+c+d+e);
	}
	
};

util = {
	init : function(){
		draggable = null;
	},
	onEnter:function(event,funct){
		if(event.keyCode==13) eval(funct);
	},
	checkRequired : function(values,namemap){
		var ervalues = '',name,value;
		valuesArray = values.split(',');
		nMArray = namemap.split(',');
			
		for (var i=0;i<=valuesArray.length-1;i++) {				
			nm = nMArray[i];
			if($(valuesArray[i])){
				name = $(valuesArray[i]).name;
				value = $F(valuesArray[i]);
				if(value == '') { 
					ervalues += nm+' is required! Please fill it in. \n';	
				}else if(name == 'email' && value.length > 0 && !util.isEmail(value)){
					ervalues +='Email is incorrect, please correct it. \n';	
				}
			}else{
				ervalues += nm+' is required! Please fill it in. \n';
			}	
		} 
		if (ervalues.length != 0){
			alert(ervalues);
			return false;
		}else{
			return true;	
		}
	},
	
	setValidate:function(className){
		validations = new Array();
		elements = new Array();
		var i = 0;
		className.each(function(c){
			$$("."+c+"").each(function(el){
				j = elements.indexOf(el.id);
				if(j == -1) {
					validations[i] = new LiveValidation(el.id, {validMessage:"",onlyOnBlur:true});
					validations[i].add( Validate[c.capitalize()] );
					i++;
				} else {
					validations[j].add( Validate[c.capitalize()] );
				}
				elements.push(el.id);
			});
		});
	},
	addValidation:function(el,type,params){
		// var i = 0;
		i = elements.indexOf(el.id);
		if(i == -1) {
			v = new LiveValidation(el.id, {validMessage:"",onlyOnBlur:true});
			v.add( Validate[type.capitalize()], params );
			validations.push(v);
		} else {
			validations[i].add( Validate[type.capitalize()], params );
		}
		elements.push(el.id);
	},
	toPts:function(v){
		var units = $F('units');
		if (units == 2) {
			// for mm
			return v*2.834645669
		} else if (units == 3){
			// for picas
		} else {
			// default to inches
			return v*72;
		}
	},
	clearArray : function(arr){
		arr.length = 0;
	},
	zeroFill: function(n, totalDigits){ 
	   n = n.toString(); 
	   var pd = ''; 
	   if(totalDigits > n.length){ 
	      for(i=0; i<(totalDigits-n.length);i++){ 
	        pd += '0'; 
	      }
	   } 
	   return pd+n.toString();
	},
	getMonthsArray : function(abrv){
		return (abrv)?
			new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'):
			new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	},
	gup:function(url,name){
	  exp = "[\\?&]"+name+"=([^&#]*)";
	  regex = new RegExp(exp);
	  res = regex.exec(url);
	  return (res == null)?"":res[1];	
	},
	isNumeric:function(n){
		return (!isNaN(n))?true:false;
	},
	isFloat:function(n){
		return ((q % 1) == 0)?false:true;
	},
	isWithinBounds:function(n, min, max){
		n = parseFloat(n);
		return (n >= min && n <= max);
	},
	isSpecialCharacter:function(elem){
		var iChars = "!#$%^&*()+=[]\\\';,/{}|\":<>?";
		for (var i = 0; i < elem.value.length; i++) {
		  	if (iChars.indexOf(elem.value.charAt(i)) != -1) {
		  		// alert ("Your query has special characters. \nThese are not allowed.\n Please remove them and try again.");
		  		return true;
		  	}
		}
	},
	padNumber:function(number, padLength){
	   	number += '';
		while(number.length < padLength) {
			number = '0'+number;
		}
		return number;
	},
	hasSpaces : function(string){
		return (string.indexOf(" ") != "-1")?true:false;
	},
	isEmail : function(email){
		re = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
		return (!re.test(email))?false:true;
	},
	encode:function(str){
		return "ccid="+Base64.encode(str);
	},
	enc: function(str){
	    lenStrMsg=str.length;
	    encMsg="";
	    for (pos = 0; pos<lenStrMsg; pos++){
	        key = ((lenStrMsg+pos)+1); // (+5 or *3 or ^2)
	        key = (255+key) % 255;
	        byteToBeEnc = str.substr(pos, 1);
	        numByteEncrypt = byteToBeEnc.charCodeAt(0);
	        xByte = numByteEncrypt ^ key;  
	        encByte = String.fromCharCode(xByte);
	        encMsg += encByte;
	    }
	    return encMsg;
	},
stripNonNumeric:function(num){
		var v = "0123456789";
		var nNum = "";
		for (i=0; i < num.length; i++) {
			cNum = num.charAt(i);
			if(v.indexOf(cNum,0) != -1)
			nNum += cNum;
		}
		return nNum;
	},

	
	validateMaxChars:function(el, max){
		if(el.value.length > max){
			if ($('error'+el.id)) {
				//console.log("too much text, error already shown");
			} else {
				el.insert({after: '<div id="error' + el.id + '" style="color:red;">Field limited to ' + max + ' characters. Please edit.'});
			}
			// el.activate(); doesn't work
		}
	},
	validateFormValueForStorage:function(evt,el) {
		// console.log("Got char: " + evt.charCode);
		var charCode = evt.charCode;
		if(charCode != 0 && charCode != 46) {
			if((charCode >= 65 && charCode <= 97) || (charCode >= 90 && charCode <= 122) 
				|| (charCode >= 48 && charCode <= 57) || (charCode == 45) || (charCode == 95)){
				return true;
			} else {
				evt.preventDefault();
				if (!($('error' + el.id))) {
					el.insert({after: '<div id="error' + el.id + '" style="color:red;">No special characters allowed.'});

				};

			}
		}
	},
	toggleDiv:function(id){
		if ($(id).visible()) {
			$(id).hide();
		} else {
		    $(id).show();
		};
	},
	getFlObject:function(name) {
	    if (navigator.appName.indexOf("Microsoft") != -1) {
	        return window[name];
	    } else {
	        return document[name];
	    }
	}

	
};

var sorttable = Class.create({
  initialize: function(className, options) {
	this.options = Object.extend({
		classNames : {
			oddRow : 'oddRow',
			evenRow : 'evenRow',
			sortAsc : 'sortasc',
			sortDesc : 'sortdesc'
		}}, options || {});
		
	this.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
	this.tables = $$('.'+className);
	this.colomnSortedTable = "";
	$A(this.tables).each(function(table){
		
		if(!table.getAttribute("sorted")){
			table.writeAttribute("sorted","true");
			this.makeSortable(table);
		}
	}.bind(this));
	this.stripeRows();
  },
  makeSortable:function(table){
	headrow = table.tHead.rows[0].cells;
    for (var i=0; i<headrow.length; i++) {
      if (!headrow[i].className.match(/\bnosort\b/)) { // skip this col
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
        if (mtch) override = mtch[1];
	    	headrow[i].sorttable_sortfunction = (mtch && typeof sorttable["sort_"+override] == 'function')?sorttable["sort_"+override]:this.guessType(table,i);
	    	headrow[i].sorttable_columnindex = i;
	   	//IE is pure evil
			if(Prototype.Browser.IE){
				Event.observe(headrow[i], 'click', this.forward.bindAsEventListener(headrow[i],this,table.tBodies[0]));
			}else{
				headrow[i].onclick = this.forward.bindAsEventListener(headrow[i],this,table.tBodies[0]);
			}
	   }
	}
  },
  stripeRows:function(){
	this.tables.each(function(table){
		tbody = table.tBodies[0];
		rows = tbody.rows;
		dark =(table.hasClassName('dark'))?true:false;
		for (var i=0; i<rows.length; i++) {
			even = (dark)?'rowevenDark':'roweven';
			odd = (dark)?'rowoddDark':'rowodd';
			var css = ((i+1)%2 === 0 ?even:odd);
			var cn = rows[i].className.split(/\s+/);
			var newCn = [];
			for(var x = 0, l = cn.length; x < l; x += 1) {
				if(cn[x] !== even && cn[x] !== odd) 
					newCn.push(cn[x]); 
			}
			newCn.push(css);
			rows[i].className = newCn.join(" ");
		}
	});
  },
  guessType: function(table, column) {
	// guess the type of a column based on its first non-blank row
    sortfn = this.sort_alpha;
    for (var i=0; i<table.tBodies[0].rows.length; i++) {
		text = this.getInnerText(table.tBodies[0].rows[i].cells[column]);
		if(text != ''){
        if(text.match(/^-?[£$?]?[\d,.]+%?$/))
          return this.sort_numeric;
     
        possdate = text.match(this.DATE_RE)
		
        if(possdate){
          first = parseInt(possdate[1]);
          second = parseInt(possdate[2]);
          if(first > 12)
            return this.sort_ddmm;
          else if (second > 12)
            return this.sort_mmdd;
          else
            sortfn = this.sort_ddmm;
        }
      }
    }
    return sortfn;
  },
  getInnerText: function(node){
	hasInputs = (typeof node.getElementsByTagName == 'function') && node.getElementsByTagName('input').length;
    if (node.getAttribute("sorttable_customkey") != null) {
	  return node.getAttribute("sorttable_customkey");
    }else if (typeof node.textContent != 'undefined' && !hasInputs) {
    	return node.textContent.replace(/^\s+|\s+$/g, '');
    }else if (typeof node.innerText != 'undefined' && !hasInputs) {
    	return node.innerText.replace(/^\s+|\s+$/g, '');
    }else if (typeof node.text != 'undefined' && !hasInputs) {
    	return node.text.replace(/^\s+|\s+$/g, '');
    }else {
	  switch (node.nodeType) {
        case 3:
	      if (node.nodeName.toLowerCase() == 'input') {
            return node.value.replace(/^\s+|\s+$/g, '');
          }
        case 4:
	      return node.nodeValue.replace(/^\s+|\s+$/g, '');
          break;
        case 1:
			var innerText = '';
	          for (var i = 0; i < node.childNodes.length; i++) {
	            if(node.childNodes[i].value){
					innerText = node.childNodes[i].value;
					return innerText.replace(/^\s+|\s+$/g, '');
				}
	          }		
			return '';
        case 11:
	      var innerText = '';
          for (var i = 0; i < node.childNodes.length; i++) {
            innerText += this.getInnerText(node.childNodes[i]);
          }
          return innerText.replace(/^\s+|\s+$/g, '');
          break;
        default:
	      return '';
      }
    }
  },
  forward : function(e,t,tBody){
		var el = Event.element(e);
		sd = t.options.classNames.sortDesc;
		sa = t.options.classNames.sortAsc;
		if ($(el).hasClassName(sd)){
		//more IE evil  
		if(Prototype.Browser.IE) Event.stopObserving(el, 'click',t,tBody);
		
		t.reverse(tBody);
		el.className = el.className.replace(sd,sa);
        	return;
        }
		
        if(el.hasClassName(sa)) {
		  t.reverse(tbody);
          el.className = el.className.replace(sa,sd);
          return;
        }
		
        $A(el.parentNode.childNodes).each(function(cell){
			if(cell.nodeType == 1) {
		     	$(cell).removeClassName(sa);
		        $(cell).removeClassName(sd);
		     }
		});
        el.addClassName(sd);

	    rowArray = [];
	        col = el.sorttable_columnindex;
	        rows = $A(tbody.rows);
			rows.each(function(row){
				rowArray[rowArray.length] = [t.getInnerText(row.cells[col]), row];
			}.bind(this));
			
	        rowArray.sort(el.sorttable_sortfunction);
	       
			for (var j=0; j<rowArray.length; j++) {
	          tbody.appendChild(rowArray[j][1]);
	        }
	        delete rowArray;
			t.stripeRows();
  },
  reverse: function(tbody){
	newrows = [];
    for (var i=0; i<tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (var i=newrows.length-1; i>=0; i--) {
       tbody.appendChild(newrows[i]);
    }
    delete newrows;
	this.stripeRows();
  }, 
  sort_numeric: function(a,b) {
    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
  },
  sort_alpha: function(a,b) {
    if (a[0]==b[0]) return 0;
    if (a[0]<b[0]) return -1;
    return 1;
  },
  sort_ddmm: function(a,b) {
	mtch = a[0].match(this.DATE_RE);
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(this.DATE_RE);
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  },
  sort_mmdd: function(a,b) {
    mtch = a[0].match(this.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(this.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  }  
});

var UI = Class.create({
	initialize : function(){

	},
	setAllSortable : function(){
		s = new sorttable('sortable');
		//console.log();
		dragtable.init();
		//d = new dragtable();
	},
	setEnterAction : function(elem,action){
		var enterAction = function(event){ 
			if(event.keyCode==13){ 
				 eval(action);
			}
		};
		Event.observe(elem, 'keypress',enterAction);
	},
	request:function(action,klass,params,onComplete){
		
		qps = (params)?Object.toQueryString(params):"";
		onComplete = onComplete || "";
		pBody = 'action='+action+'&class='+klass+'&'+qps;
		new Ajax.Request(loc, {postBody:pBody,onComplete:onComplete});
	},
	update:function(container,action,klass,params,onComplete,insertion){
		insertion = insertion || false; //after, before, top, bottom - 4 options.
		qps = (params)?Object.toQueryString(params):"";
		onComplete = onComplete || "";
		pBody = 'action='+action+'&class='+klass+'&'+qps;
		new Ajax.Updater(container,loc, {postBody:pBody,onComplete:onComplete,insertion:insertion});
	},
	updateDateCell : function(cellId) {	
		if($(cellId)){
			t = "";
			zero = "";
			d = new Date();
			ch = d.getHours();
			cm = d.getMinutes();	
			t =(ch<12)?"am":"pm";
			if (ch == 0)ch = 12;
			if (ch > 12)ch = ch - 12;
			if (cm < 10){zero = '0';}
			d = ch + ":" + zero + cm + " " + t;
			$(cellId).innerHTML='Today &nbsp;&nbsp;'+d;
		}
	},
	fade:function(el){
		Element.hide(el);
	},
	appear:function(el){
		Effect.Appear(el,{duration:0.5});
	},
	findDraggable:function(){
		objs = $$('.draggable');
		objs.each(function(obj){
			if(obj.nodeName != 'TABLE'){
				if (obj.id == 'specTrim') {
				adSpec.draggableSpecTrim(obj);
				} else {
				new Draggable(obj);
				};
			}
		});
	},
	disableButton:function(el){
		el.tmpclick = el.onclick;
		el.onclick = "";
		el.style.cursor = 'none';
		el.style.opacity = .2;
	},
	enableButton:function(el){
		if(el.tmpclick) el.onclick = el.tmpclick; 
		el.style.cursor = 'pointer';
		el.style.opacity = 1;
	},
	removeTableRow : function(rowId){
		if($(rowId)) $(rowId).parentNode.removeChild($(rowId));
	},
	getSelectorLabel : function(elem){
		return $(elem).options[$(elem).selectedIndex].innerHTML;
	},
	reverseSelection:function(){
		util.clearArray(SMA.actionQueue);
		cbs = $$('.checkboxAction');
		cbs.each(function(cb){
			if(cb.checked){
				cb.checked = false;
			}else{
				if($('row'+$(cb).value).visible()){
					cb.checked = true;
					SMA.addToActionQueue(cb);
				}
			}
		});
	},
	deselectAll:function(){
		cbs = $$('.checkboxAction');
		cbs.each(function(cb){
			cb.checked = false;
		});
		util.clearArray(SMA.actionQueue);
	},
	selectAll:function(){
		cbs = $$('.checkboxAction');
		cbs.each(function(cb){
			if($('row'+$(cb).value).visible()){
				cb.checked = true;
				SMA.addToActionQueue(cb);
			}
		});
	},
	hideSelects:function(){
		var selects = $$('.custom');
		selects.each(function(select){
			select.hide();
		});
	},
	showSelects:function(){
		var selects = $$('.custom');
		selects.each(function(select){
			select.show();
		});
	},
	selectRow:function(name){
		$$('.row').each(function(e){e.removeClassName("rowSelected");  });
		$(name).addClassName("rowSelected");
	},
	loadCalendar:function(){
		SMA.softLoad('includes/yuiloader-min.js',function(){
			var loader = new YAHOO.util.YUILoader({
			      require: ["button","calendar","container"],
			      onSuccess: function(){}
			    });
			    loader.insert();
			});
	},
	createCal:function(container,title,dateSelected,callBack,minDate,maxDate){	
		
		if($(container)){
			
		SMA.softLoad('includes/yuiloader-min.js',function(){
			$(container).show();
			var loader = new YAHOO.util.YUILoader({
			     require: ["button","calendar","container"],
			     onSuccess: function(){
					var cal = new YAHOO.widget.CalendarGroup("cal",container, { 
						pages:3, title:title+': <span style="float:right;cursor:pointer;" onclick="$(\''+container+'\').hide();">Close</span>', 
						close:true, 
						selected:dateSelected,
						mindate:minDate,
						maxdate:maxDate
						} ); 
						cal.selectEvent.subscribe(callBack, cal, true); 
						cal.render();
						$(container).show();
					}
			    });
			    loader.insert();
			});
		}
	}
});


var Base64 = {
  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  	encode : function (input) {
    	 var output = "";
	     var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
	     var i = 0;
    	if(input == "") return ""; 
		
		input = Base64._utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
	            enc1 = chr1 >> 2;
	            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	            enc4 = chr3 & 63;
	            if (isNaN(chr2)) {
	                enc3 = enc4 = 64;
	            } else if (isNaN(chr3)) {
	                enc4 = 64;
	            }
	            output = output +
	            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
	            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
	       }
	       return output;	
	},
	_utf8_encode : function (string) {
		if(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;
		}else{
			return "";
		}
	}
};


