/* 
 * David Miglior for MyVCF.com
 * V1.0 started the 28/01/2011
 * Modifications : 
 * Description : the main object, and others functions
 */

// log on the console
function log(txt1, txt2, txt3, txt4) {
	if (window.console && console && console.log) {
		console.log(txt1) ;
		if (txt2) console.log(txt2) ;
		if (txt3) console.log(txt3) ;
		if (txt4) console.log(txt4) ;
	}
} ;


// main application 
MyVCFApp = {
	hostname: 'www.myvcf.com',
	init: function() {
	},
	blackList: function(us_id) {
		if (window.confirm(i18n.do_you_want_blacklist)) {
			$.ajax({
				type: 'POST',
				url: 'io.php',
				data: {
					action: 'blackList', 
					us_id:us_id
				},
				context: this,
				dataType: 'json',
				success: function(data) {
					welcomePage();
				}
			});
		}
	},
	// draw html table of the requests posted
	drawRequestsRequested: function(tabReceived, where) {
		log('tabReceived',tabReceived);
		var tabLastVcName = [] ;
		var lastUser = "" ;
		var txt = "" ;
		txt += "<div class='div_knowcontacts'>" ;
		txt += "<table width='100%' class='table_contacts_list' border='0' cellpadding='0' cellspacing='0'>" ;
		for (var i=0 ; i<tabReceived.length ; i++) {
			var img = "/statics/images/im_default-femme-petit.jpg" ;
			if (tabReceived[i].vc_photo!='') img = "/dynamics/ip2_"+tabReceived[i].vc_photo+".jpg" ;
			var bgTr = "background-color:#f6f6f6;" ;
			if (i%2==0) bgTr = "background-color:#eaeaea;" ;
			txt += "<tr style='"+bgTr+"'>" ;
			txt += "<td><img width='20' height='25' src='"+img+"' alt='' /></td>" ;
			txt += "<td>" ;
			var inArray = false ;
			var name = tabReceived[i].vc_firstname+" "+tabReceived[i].vc_lastname ;
			if (tabReceived[i].vc_organisation!='') {
				name += " ("+tabReceived[i].vc_organisation+")" ;
				if (tabReceived[i].vc_firstname=='' && tabReceived[i].vc_lastname=='') name = tabReceived[i].vc_organisation ;
			}
			/*
			for(var j=0 ; j<tabLastVcName.length ; j++) {
				if (tabLastVcName[j]==name) inArray = true ;
			}
			if (lastUser!=tabReceived[i].us_id) txt += "<div><a href='javascript:void(0);' onclick=\"linkPage('"+tabReceived[i].us_id+"', 2)\">" ;
			if (!inArray && lastUser==tabReceived[i].us_id) txt += ", " ;
			if (!inArray) txt += name+"" ;
			*/
			txt += "<div><a href='javascript:void(0);' onclick=\"linkPage('"+tabReceived[i].us_id+"', 2)\">"+name+"</a></div>" ;

			lastUser = tabReceived[i].us_id ;
			if (!inArray) tabLastVcName.push(name) ;
			txt += "</td>" ;
			txt += "<td>"+i18n.ask_the+" "+MyVCFApp.formatDate(tabReceived[i].re_date_requested)+"</td>" ;
			txt += "<td id='td_requestsrequested_"+tabReceived[i].vc_id+"'></td>" ;
			txt += "</tr>" ;
		}
		txt += "</table>" ;
		txt += "</div>" ;
		where.html(txt) ;
		for (var i=0 ; i<tabReceived.length ; i++) {
			var bt = new MyVCFApp.Button({
				text: i18n.see_and_valid,
				scope: this,
				re_id: tabReceived[i].us_id,
				onClick: function(evt) {
					linkPage(evt.data.view.re_id, 2) ;
				}
			}) ;
			bt.render($("#td_requestsrequested_"+tabReceived[i].vc_id)) ;
		}
	},
	// draw the html requests sended
	drawRequestsSended: function(tabSended, where) {
		var txt = "" ;
		txt += "<div class='div_knowcontacts'>" ;
		txt += "<table width='100%' class='table_contacts_list' border='0' cellpadding='0' cellspacing='0'>" ;
		for (var i=0 ; i<tabSended.length ; i++) {
			var img = "/statics/images/im_default-femme-petit.jpg" ;
			if (tabSended[i].vc_photo!='') img = "/dynamics/ip2_"+tabSended[i].vc_photo+".jpg" ;
			var bgTr = "background-color:#f6f6f6;" ;
			if (i%2==0) bgTr = "background-color:#eaeaea;" ;
			txt += "<tr style='"+bgTr+"'>" ;
			txt += "<td><img width='20' height='25' src='"+img+"' alt='' /></td>" ;
			txt += "<td><a href='javascript:void(0);' onclick=\"linkPage('"+tabSended[i].re_id+"', 1)\">"+tabSended[i].vc_firstname+" "+tabSended[i].vc_lastname+"</a></td>" ;
			txt += "<td>"+i18n.ask_the+" "+MyVCFApp.formatDate(tabSended[i].re_date_requested)+"</td>" ;
			txt += "<td id='td_requestssended_"+tabSended[i].vc_id+"'></td>" ;
			txt += "</tr>" ;
		}
		txt += "</table>" ;
		txt += "</div>" ;
		where.html(txt) ;
		for (var i=0 ; i<tabSended.length ; i++) {
			var bt = new MyVCFApp.Button({
				text: "Voir et valider",
				scope: this,
				re_id: tabSended[i].re_id,
				onClick: function(evt) {
					linkPage(evt.data.view.re_id, 1) ;
				}
			}) ;
			bt.render($("#td_requestssended_"+tabSended[i].vc_id)) ;
		}
	},
	// draw the last 10 contacts
	drawLastContacts: function(tabLastContacts, where) {
		var txt = "" ;
		txt += "<div class='div_knowcontacts'>" ;
		txt += "<table width='100%' class='table_contacts_list' border='0' cellpadding='0' cellspacing='0'>" ;
		for (var i=0 ; i<tabLastContacts.length ; i++) {
			var img = "/statics/images/im_default-femme-petit.jpg" ;
			if (tabLastContacts[i].vc_photo!='') img = "/dynamics/ip2_"+tabLastContacts[i].vc_photo+".jpg" ;
			var bgTr = "background-color:#f6f6f6;" ;
			if (i%2==0) bgTr = "background-color:#eaeaea;" ;
			txt += "<tr style='"+bgTr+"'>" ;
			txt += "<td><img width='20' height='25' src='"+img+"' alt='' /></td>" ;
			txt += "<td><a href='javascript:void(0);' onclick=\"contactsPage('','"+tabLastContacts[i].vc_id+"');\">"+tabLastContacts[i].vc_firstname+" "+tabLastContacts[i].vc_lastname+"</a></td>" ;
			txt += "</tr>" ;
			if (i>=10) break ;
		}
		txt += "</table>" ;
		txt += "</div>" ;
		where.html(txt) ;
	},
	// draw the friends
	drawKnowPerhaps: function(tabFriends, where) {
		var txt = "" ;
		txt += "<div class='div_knowcontacts'>" ;
		txt += "<table width='100%' class='table_contacts_list' border='0' cellpadding='0' cellspacing='0'>" ;
		for (var i=0 ; i<tabFriends.length ; i++) {
			var img = "/statics/images/im_default-femme-petit.jpg" ;
			if (tabFriends[i].vc_photo!='') img = "/dynamics/ip2_"+tabFriends[i].vc_photo+".jpg" ;
			var bgTr = "background-color:#f6f6f6;" ;
			if (i%2==0) bgTr = "background-color:#eaeaea;" ;
			txt += "<tr style='"+bgTr+"'>" ;
			txt += "<td><img width='20' height='25' src='"+img+"' alt='' /></td>" ;
			txt += "<td><a href='javascript:void(0);' onclick=\"linkPage('"+tabFriends[i].vc_id+"', 0)\">"+tabFriends[i].vc_firstname+" "+tabFriends[i].vc_lastname+"</a></td>" ;
			txt += "</tr>" ;
		}
		txt += "</table>" ;
		txt += "</div>" ;
		where.html(txt) ;
	},
	// init the opened page
	initPage: function(divPage, numMenu) {
		$("#div_arrowallcards").hide() ;
		var tabPages = [
			'div_main_contacts', 
			'div_main_managecard', 
			'div_main_welcome', 
			'div_main_faq', 
			'div_main_plugins', 
			'div_main_account', 
			'div_main_import', 
			'div_main_link'
		] ;
		for(var i=0 ; i<tabPages.length ; i++) {
			if (divPage!=tabPages[i]) $("#"+tabPages[i]).slideUp() ;
		}
		$("#"+divPage).slideDown('fast', function() {
			if (divPage=='div_main_managecard') {
				window.setTimeout("MyVCFApp.ManageCards.moveArrow()", 200) ;
				//alert("toto") ;
			}
		}) ;
		$(".menucontent .left, .menucontent .right").removeClass('on') ;
		$("#menucontent"+numMenu).addClass('on') ;
	},
	// render the view
	setView: function(view, jqEl) {
		jqEl.html("") ;
		view.render(jqEl) ;
	},
	// utils to parse an sql date and return an date object
	parseDate: function(d) {
		//var d = date.substring(0,10) ;
		return new Date(d.substring(0,4), d.substring(5,7), d.substring(8,10), d.substring(11,13), d.substring(14,16), d.substring(17,19)) ;
	},
	// add an initial zero if < 10 and return a string
	addZeroPerhaps: function(num) {
		if (num<10) return "0"+num ;
		return num ;
	},
	// return the singular of the plurial of an string
	plurial: function(nb, singular, plurial) {
		if (nb>1) return nb+" "+plurial ;
		else return nb+" "+singular ;
	},
	// format date 
	formatDate: function(date) {
		var d = this.parseDate(date) ;
		var res = this.addZeroPerhaps(d.getDate())+"/"+this.addZeroPerhaps(d.getMonth())+"/"+this.addZeroPerhaps(d.getFullYear())+" à "+this.addZeroPerhaps(d.getHours())+":"+this.addZeroPerhaps(d.getMinutes()) ;
		return res ;
	},
	// draw the myvcf card !!!
	// jqEl : the jQuery element where to display
	// isEdit=true if edit mode
	drawCard: function(jqEl, isEdit) {
		var idCard = MyVCFApp.Utils.nextId() ;
		//this.idCardLinked = MyVCFApp.Utils.nextId() ;
		var cls = '' ;
		if (isEdit) cls = 'cardEdit' ;
		var txt = "" ;
		// html for the main card
		//txt += "<div style=''>titi</div>" ;
		txt += "<div class='card' id='"+idCard+"'><div class='content'><div style='position:relative; width:0; height:0;'><div style='position:absolute; top:-28px; left:0; width:500px; text-align:right;' class='div_block_lincked'></div></div>" ;
		txt += "<div style='float:left; width:130px;' class='"+cls+" div_block_img'></div>" ;
		txt += "<div style='float:left; width:380px;' class='"+cls+"'>" ;
			txt += "<div class='div_block_name'></div>" ;
			txt += "<div class='clear'></div>" ;
			txt += "<div class='div_block_organisation'></div>" ;
			txt += "<div class='clear'></div>" ;
			txt += "<div class='div_block_address' style='width:350px;'></div>" ;
			txt += "<div class='clear'></div>" ;
			txt += "<div class='div_block_tels'>" ;
				//txt += this.addTelCard("Tél. bureau", "+33.x xx xx xx xx") ;
				//txt += this.addTelCard("Fax. bureau", "+33.x xx xx xx xx") ;
				//txt += this.addTelCard("Tél. portable", "+33.x xx xx xx xx") ;
			txt += "</div>" ;
			txt += "<div class='clear'></div>" ;
			txt += "<div class='div_block_emails'>" ;
				//txt += this.addTelCard("eMail", "eMail personnel") ;
				//txt += this.addTelCard("Site web", "Site internet") ;
			txt += "</div>" ;
			txt += "<div class='clear'></div>" ;
			txt += "<div class='div_block_comment'></div>" ;
			txt += "<div class='clear'></div>" ;
		txt += "</div>" ;
		txt += "<div class='clear'></div>" ;
		txt += "</div><div class='bottom'></div></div>" ;
		jqEl.html(txt) ;
		if (isEdit) {
			// create events for edit mode
			$("#"+idCard+" .div_block_name, #"+idCard+" .div_block_organisation, #"+idCard+" .div_block_tels, #"+idCard+" .div_block_address, #"+idCard+" .div_block_emails, #"+idCard+" .div_block_comment").mouseenter(function() {
				$(this).addClass('overEdit') ;
			}).mouseleave(function() {
				$(this).removeClass('overEdit') ;
			}) ;
			//$("#div_block_name").click({view:this}, this.showWinForName) ;
			$("#"+idCard+" .div_block_name").click({view:MyVCFApp.ManageCards}, function(evt) {
				evt.data.view.showWinForName.apply(evt.data.view.scope, arguments) ;
			}) ;
			$("#"+idCard+" .div_block_organisation").click({view:MyVCFApp.ManageCards}, function(evt) {
				evt.data.view.showWinForOrganisation.apply(evt.data.view.scope, arguments) ;
			}) ;
			$("#"+idCard+" .div_block_address").click({view:MyVCFApp.ManageCards}, function(evt) {
				evt.data.view.showWinForAddresses.apply(evt.data.view.scope, arguments) ;
			}) ;
			$("#"+idCard+" .div_block_tels").click({view:MyVCFApp.ManageCards}, function(evt) {
				evt.data.view.showWinForTelephons.apply(evt.data.view.scope, arguments) ;
			}) ;
			$("#"+idCard+" .div_block_emails").click({view:MyVCFApp.ManageCards}, function(evt) {
				evt.data.view.showWinForEmails.apply(evt.data.view.scope, arguments) ;
			}) ;
			$("#"+idCard+" .div_block_comment").click({view:MyVCFApp.ManageCards}, function(evt) {
				evt.data.view.showWinForNotes.apply(evt.data.view.scope, arguments) ;
			}) ;
			$("#"+idCard+" .div_block_img").click({view:MyVCFApp.ManageCards}, function(evt) {
				evt.data.view.showWinForImg.apply(evt.data.view.scope, arguments) ;
			}) ;
		}
		return idCard ;
	},
	// add a line of telephone
	addTelCard: function(type, num) {
		var typeTxt = "" ;
		if (type<10) typeTxt = MyVCFApp.Utils.searchInSimpleArray(MyVCFApp.Utils.getTypesTelephon(), type, 1) ;
		else typeTxt = MyVCFApp.Utils.searchInSimpleArray(MyVCFApp.Utils.getTypesEmail(), type, 1) ;
		txt = "" ;
		txt += "<div style='float:left; width:100px; font-weight:bold; color:#00AEF0;'>"+typeTxt+"</div><div style='float:left; width:250px;'>"+num+"</div><div class='clear'></div>" ;
		return txt ;
	},
	searchLinked: function(vc_id) {
		contactsPage(vc_id) ;
	},
	// update the card
	updateCard: function(idCard, data, isEdit) {
		//log("updateCard", data) ;
		MyVCFApp.currentCard = data ;
		if (isEdit) {
			//$("#a_cardname_"+data.vc_id).html("<img width='83' height='50' src='/dynamics/pp_"+data.vc_id+".png?d="+(new Date()).getMilliseconds()+"' alt='' /><br/>"+data.vc_cardname) ;
			$(".div_manage_allcards").removeClass('on') ;
			$("#a_cardname_"+data.vc_id).parent().addClass('on') ;
			$("#tf_managecards_vc_cardname").val(data.vc_cardname) ;
			$("#span_managecard_name_"+data.vc_id).html(data.vc_cardname) ;
			$("#tf_managecards_mainlink").val("http://"+MyVCFApp.hostname+"/"+data.vc_cardname) ;
			$("#tf_managecards_vc_right").val(data.vc_right) ;
			//var p = $("#a_cardname_"+data.vc_id).position() ;
			//var w = $("#a_cardname_"+data.vc_id).width() ;
			MyVCFApp.ManageCards.moveArrow() ;
			MyVCFApp.ManageCards.generateFacebook(data.vc_cardname, data.vc_firstname+" "+data.vc_lastname) ;
			$("#"+idCard+" .div_block_lincked").html("<a href='javascript:void(0);' onclick=\"MyVCFApp.searchLinked('"+data.vc_id+"');\">"+this.plurial(data.nbRelations,"contact lié","contacts liés")+" à cette carte</a>") ;
			//var p2 = $("#a_cardname_"+data.vc_id).position() ;
			//window.setTimeout(function() {
				//$("#div_arrowallcards").css({top:p.top+31, left:Math.ceil(p.left+w/2)-12}) ;
			//}, 1000) ;
		}	
		if (isEdit && MyVCFApp.Utils.isEmpty(data.vc_name) && MyVCFApp.Utils.isEmpty(data.vc_firstname)) {
			$("#"+idCard+" .div_block_name").removeClass('ok').html("<span class='lightgrey'>"+i18n.civility_name_firstname+"</span>") ;
		} else {
			$("#"+idCard+" .div_block_name").addClass('ok').html(data.vc_firstname+" "+data.vc_lastname) ;
		}
		
		if (isEdit && MyVCFApp.Utils.isEmpty(data.vc_photo)) {
			$("#"+idCard+" .div_block_img").removeClass('ok').html("<img src='/statics/images/im_default-femme.jpg' alt='' />") ;
		} else {
			if (data.vc_photo!='') $("#"+idCard+" .div_block_img").addClass('ok').html("<img src='/dynamics/ip_"+data.vc_photo+".jpg' alt='' />") ;
			else $("#"+idCard+" .div_block_img").addClass('ok').html("<img src='/statics/images/im_default-femme.jpg' alt='' />") ;
		}
		
		if (isEdit && MyVCFApp.Utils.isEmpty(data.vc_title) && MyVCFApp.Utils.isEmpty(data.vc_organisation)) {
			$("#"+idCard+" .div_block_organisation").removeClass('ok').html("<span class='lightgrey'>"+i18n.society_function+"</span>") ;
		} else {
			var tT = data.vc_organisation ;
			if (data.vc_organisation!='' && data.vc_title!='') tT += " - " ;
			tT += data.vc_title ;
			$("#"+idCard+" .div_block_organisation").addClass('ok').html(tT) ;
		}
		
		if (isEdit && data.tabAddresses.length==0) {
			$("#"+idCard+" .div_block_address").removeClass('ok').html("<span class='lightgrey'>"+i18n.address+" 1<br/>"+i18n.address+" 2<br/>"+i18n.zip+" "+i18n.city+"<br/>"+i18n.country+"<br/></span>") ;
		} else {
			var txt = "" ;
			txt += "<table border='0' cellpadding='0' cellspacing='0' width='100%'>" ;
			for(var i=0 ; i<data.tabAddresses.length ; i++) {
				if (i%2==0) txt += "<tr>" ;
				var sTemp = "padding:0 0 10px 0;" ;
				if (i%2==0) sTemp = "padding:0 20px 10px 0;" ;
				txt += "<td valign='top' width='50%' style='"+sTemp+"'>"+MyVCFApp.Utils.formatAddress(data.tabAddresses[i])+"</td>" ;
				if (i%2==1) txt += "</tr>" ;
			}
			txt += "</table>" ;
			/*
			for(var i=0 ; i<data.tabAddresses.length ; i++) {
				txt += "<div style='float:left; margin:0 20px 10px 0; width:165px;'>"+MyVCFApp.Utils.formatAddress(data.tabAddresses[i])+"</div>" ;
			}
			*/
			$("#"+idCard+" .div_block_address").addClass('ok').html(txt) ;
		}
		
		
		
		
		var tabTels = [],
			tabEmails = [] ;
		for(var i=0 ; i<data.tabTelephons.length ; i++) {
			if (data.tabTelephons[i].te_type<10) tabTels.push(data.tabTelephons[i]) ;
			else tabEmails.push(data.tabTelephons[i]) ;
		}
		//log("tabTels", tabTels) ;
		//log("tabEmails", tabEmails) ;
		if (isEdit && tabTels.length==0) {
			var txt = "" ;
			txt += this.addTelCard(1, "<span class='lightgrey'>+33.x xx xx xx xx</span>") ;
			txt += this.addTelCard(3, "<span class='lightgrey'>+33.x xx xx xx xx</span>") ;
			txt += this.addTelCard(4, "<span class='lightgrey'>+33.x xx xx xx xx</span>") ;
			$("#"+idCard+" .div_block_tels").removeClass('ok').html(txt) ;
		} else {
			var txt = "" ;
			for(var i=0 ; i<tabTels.length ; i++) {
				txt += ""+this.addTelCard(tabTels[i].te_type, tabTels[i].te_num)+"" ;
			}
			$("#"+idCard+" .div_block_tels").addClass('ok').html(txt) ;
		}

		if (isEdit && tabEmails.length==0) {
			var txt = "" ;
			txt += this.addTelCard(11, "<span class='lightgrey'>myname@provider.com</span>") ;
			txt += this.addTelCard(13, "<span class='lightgrey'>http://www.my-website.com</span>") ;
			$("#"+idCard+" .div_block_emails").removeClass('ok').html(txt) ;
		} else {
			var txt = "" ;
			for(var i=0 ; i<tabEmails.length ; i++) {
				var txtValid = "" ;
				if (isEdit && tabEmails[i].te_valid==0) txtValid = " <span class='red'>("+i18n.not_valid+")</span>" ;
				txt += ""+this.addTelCard(tabEmails[i].te_type, tabEmails[i].te_num+txtValid)+"" ;
			}
			$("#"+idCard+" .div_block_emails").addClass('ok').html(txt) ;
		}





		if (isEdit && MyVCFApp.Utils.isEmpty(data.vc_notes)) {
			$("#"+idCard+" .div_block_comment").removeClass('ok').html("<span class='lightgrey'>"+i18n.notes_comment_hobbies+"</span>") ;
		} else {
			$("#"+idCard+" .div_block_comment").addClass('ok').html(data.vc_notes) ;
		}
	}
} ;


// Instancied object, all utils functions
MyVCFApp.Utils = new (function() {
	this._myId = 0 ;
	// return the next id
	this.nextId = function() {
		return 'myvcf_'+(this._myId++) ;
	} ;
	// return true if v is null, undefined or empty
	this.isEmpty = function(v, allowBlank){
		return (v === null || v === undefined || (!allowBlank ? v === "" : false));
	} ;
	// return true if txt length dont exeed len
	this.validMinLength = function(txt, len) {
		if (txt.length<len) return false ;
		return true ;
	} ;
	// return true if txt is a valid email
	this.validEmail = function(txt) {
	// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
		return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(txt);
	} ;
	// return true if pass1==pass2 and pass1>=6
	this.validPass = function(pass1, pass2) {
		if (pass1!=pass2) return false ;
		if (!this.validMinLength(pass1, 6)) return false ;
		return true ;
	} ;
	// center the jquery element jqEl (jqEl must be absolute position)
	this.centerEl = function(jqEl) {
		jqEl.css("top",Math.ceil(($(window).height()-jqEl.outerHeight())/2)+$(window).scrollTop()).css("left",Math.ceil(($(document).width()-jqEl.outerWidth())/2)) ;
	} ;
	// format address with br at the end of lines
	this.formatAddress = function(ad) {
		var txt = "" ;
		if (!MyVCFApp.Utils.isEmpty(ad.ad_address1)) txt += ad.ad_address1+"<br/>" ;
		if (!MyVCFApp.Utils.isEmpty(ad.ad_address2)) txt += ad.ad_address2+"<br/>" ;
		var txt2 = "" ;
		if (!MyVCFApp.Utils.isEmpty(ad.ad_zip)) txt2 += ad.ad_zip+" " ;
		if (!MyVCFApp.Utils.isEmpty(ad.ad_city)) txt2 += ad.ad_city+" " ;
		if (!MyVCFApp.Utils.isEmpty(ad.ad_region)) txt2 += ad.ad_region+" " ;
		if (txt2!='') txt2 += "<br/>" ;
		txt += txt2 ;
		
		if (!MyVCFApp.Utils.isEmpty(ad.ad_country)) txt += ad.ad_country+"<br/>" ;
		return txt ;
	} ;
	// return the 
	this.searchInSimpleArray = function(tab, key, indexToGet) {
		for(var i=0 ; i<tab.length ; i++) {
			if (tab[i][0]==key) return tab[i][indexToGet] ;
		}
		return "" ;
	} ;
	this.getTypesTelephon = function() {
		return i18n.tabTypesTel ;
	} ;
	this.getTypesEmail = function() {
		return i18n.tabTypesEmails ;
	} ;
})() ;


// Objet instantié : permet de faire un calque blanc transparent sur toute la page
MyVCFApp.Modal = new (function() {
	this.hide = function() {
		$("#MyVCFAppModal").width(10).height(10).hide() ;
	} ;
	this.show = function() {
		$("#div_poszero").css('left',0).css('top',0) ;
		if ($("#MyVCFAppModal").length==0) {
			$("#div_poszero").append("<div id='MyVCFAppModal'></div>") ;
		}
		$("#MyVCFAppModal").show().css("top",0).css("left",0).css("width",$(document).width()).css("height",$(document).height()) ;
	} ;
})() ;


// Objet instantié : permet de faire une boite d'alert modale
MyVCFApp.Alert = new (function() {
	this.hide = function() {
		MyVCFApp.Modal.hide() ;
		$("#MyVCFAppAlert").hide() ;
	} ;
	this.show = function(txt) {
		MyVCFApp.Modal.show() ;
		var w = 300 ;
		var id = MyVCFApp.Utils.nextId() ;
		if ($("#MyVCFAppAlert").length==0) {
			$("#div_poszero").append("<div id='MyVCFAppAlert' class='MyVCFAppShadow'><div class='content'></div><div style='float:right;' id='"+id+"'></div><div class='clear'></div></div>") ;
			var bt = new MyVCFApp.Button({
				text: i18n.ok,
				onClick: MyVCFApp.Alert.hide
			}) ;
			bt.render($("#"+id)) ;
		}
		$("#MyVCFAppAlert .content").html(txt) ;
		MyVCFApp.Utils.centerEl($("#MyVCFAppAlert").show()) ;
	} ;
})() ;

MyVCFApp.Confirm = new (function() {
	this.hide = function() {
		MyVCFApp.Modal.hide() ;
		$("#MyVCFAppAlert").hide() ;
	} ;
	this.okbt = function() {
		MyVCFApp.Confirm.hide() ;
		MyVCFApp.Confirm.fctOk() ;
	} ;
	this.show = function(txt, fctOk) {
		MyVCFApp.Modal.show() ;
		MyVCFApp.Confirm.fctOk = fctOk ;
		var w = 300 ;
		var id = MyVCFApp.Utils.nextId() ;
		var id2 = MyVCFApp.Utils.nextId() ;
		if ($("#MyVCFAppAlert").length==0) {
			$("#div_poszero").append("<div id='MyVCFAppAlert' class='MyVCFAppShadow'><div class='content'></div><div style='float:right;' id='"+id+"'></div><div style='float:left;' id='"+id2+"'></div><div class='clear'></div></div>") ;
			var bt = new MyVCFApp.Button({
				text: i18n.ok,
				onClick: MyVCFApp.Confirm.okbt
			}) ;
			bt.render($("#"+id)) ;
			var bt2 = new MyVCFApp.Button({
				text: i18n.cancel,
				onClick: MyVCFApp.Confirm.hide
			}) ;
			bt2.render($("#"+id2)) ;
		}
		$("#MyVCFAppAlert .content").html(txt) ;
		MyVCFApp.Utils.centerEl($("#MyVCFAppAlert").show()) ;
	} ;
})() ;


// Objet de base : permet de créer un objet de base comme un bouton, une fenêtre, etc...
MyVCFApp.View = $.inherit({
	__constructor: function(props) {
		this.xtype = 'view' ;
		this.rendered = false ;
		if (!props.id) this.id = MyVCFApp.Utils.nextId() ;
		if (!props.idBody) this.idBody = null ;
		if (!props.ref) this.ref = null ;
		if (!props.items) this.items = [] ;
		if (!props.html) this.html = "" ;
		if (!props.jqEl) this.jqEl = null ;
		if (!props.renderTo) this.renderTo = null ;
		if (!props.onBeforeShow) this.onBeforeShow = null ;
		if (!props.onBeforeHide) this.onBeforeHide = null ;
		if (!props.onShow) this.onShow = null ;
		if (!props.onHide) this.onHide = null ;
		if (!props.onRender) this.onRender = null ;
		if (!props.scope) this.scope = this ;
		if (!props.renderTo) this.renderTo = $("#div_poszero") ;
		if (!props.cls) this.cls = 'MyVCFAppView' ;
		if (!props.style) this.style = '' ;
		$.extend(this, props) ;
		this._initView() ;
	},
	_initView: function() {
	},
	_generate: function() {
		var txt = "" ;
		txt += "<div style='"+this.style+"' id='"+this.id+"' class='"+this.cls+"'>" ;
		if (this.html!='') {
			txt += this.html ;
		} else {
			for(var i=0 ; i<this.items.length ; i++) {
				txt += this.items[i]._generate() ;
			}
		}
		txt += "</div>" ;
		return txt ;
	},
	_generateEvents: function() {
		for(var i=0 ; i<this.items.length ; i++) {
			this.items[i]._generateEvents() ;
		}
	},
	findByRef: function(ref) {
		if (this.ref==ref) return this ;
		for(var i=0 ; i<this.items.length ; i++) {
			var r = this.items[i].findByRef(ref) ;
			if (r) return r ;
		}
		return null ;
	},
	findByXType: function(xtype) {
		var tabOk = [] ;
		if (this.xtype==xtype) tabOk.push(this) ;
		for(var i=0 ; i<this.items.length ; i++) {
			var tabOk2 = this.items[i].findByXType(xtype) ;
			tabOk = $.merge(tabOk, tabOk2); 
		}
		return tabOk ;
	},
	findFieldByName: function(name) {
		if (this.name==name) return this ;
		for(var i=0 ; i<this.items.length ; i++) {
			var r = this.items[i].findFieldByName(name) ;
			if (r) return r ;
		}
		return null ;
	},
	getEl: function() {
		return $("#"+this.id) ;
	},
	center: function() {
		this.jqEl.css({
			top: Math.ceil(($(window).height()-this.jqEl.outerHeight())/2),
			left: Math.ceil(($(document).width()-this.jqEl.outerWidth())/2)
		}) ;
	},
	render: function(jqEl) {
		// warning, on ne peut pas faire le rendu d'un objet déjà rendu.
		if (this.rendered) return ;
		if (!jqEl) jqEl = this.renderTo ;
		this.rendered = true ;
		this.jqEl = jqEl.append(this._generate()) ;
		this._generateEvents() ;
		if (this.onRender) this.onRender.apply(this.scope, arguments) ;
		if (this._onRender) this._onRender.apply(this.scope, arguments) ;
		return this ;
	},
	setContent: function(html) {
		this.html = html ;
		$("#"+this.idBody).html(html) ;
		return this ;
	},
	hide: function() {
		if (this.onBeforeHide && !this.onBeforeHide()) return this ;
		this.getEl().hide() ;
		if (this.onHide) this.onHide() ;
		return this ;
	},
	show: function() {
		this.render() ;
		this.getEl().hide() ;
		if (this.onBeforeShow && !this.onBeforeShow()) return this ;
		this.getEl().show() ;
		if (this.onShow) this.onShow() ;
		return this ;
	},
	showAt: function(x, y) {
		this.show() ;
		this.jqEl.css({
			left: x,
			top: y
		}) ;
		return this ;
	}
}) ;



MyVCFApp.Button = $.inherit(MyVCFApp.View, {
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppButton' ;
		this.__base(props) ;
		if (!this.text) this.text = '' ;
		if (!this.onClick) this.onClick = null ;
		this.xtype = 'button' ;
	},
	setText: function(text) {
		this.text = text ;
	},
	setAction: function(action) {
		this.onClick = action ;
	},
	_generate: function() {
		return "<table style='"+this.style+"' id='"+this.id+"' class='"+this.cls+"' border='0' cellpadding='0' cellspacing='0'><tr><td class='left'><div></div></td><td class='center'><div>"+this.text+"</div></td><td class='right'><div></div></td></tr></table>" ;
		
	},
	_generateEvents: function() {
		if (this.onClick) this.getEl().click({view:this}, function(evt) {
			evt.data.view.onClick.apply(evt.data.view.scope, arguments) ;
		}) ;
	}
}) ;

MyVCFApp.WinProperties = $.inherit(MyVCFApp.View, {
	idClose: null,
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppWinProperties' ;
		this.__base(props) ;
		this.idBody = MyVCFApp.Utils.nextId() ;
		this.idClose = MyVCFApp.Utils.nextId() ;
		this.xtype = 'winproperties' ;
	},
	_generate: function() {
		var txt = "" ;
		txt += "<div id='"+this.id+"' style='"+this.style+"' class='"+this.cls+"'>" ;
			txt += "<div style='width:0;height:0;position:relative;'><div id='"+this.idClose+"' class='close'></div></div>" ;
			txt += "<div class='content' id='"+this.idBody+"'>" ;
				this.cls = '' ;
				txt += this.__base() ;
			txt += "</div>" ;
		txt += "</div>" ;
		return txt ;
	},
	_generateEvents: function() {	
		this.__base() ;
		$("#"+this.idClose).css({left:$('#'+this.id).width()-10, top:0}).click({view:this}, function(evt) {
			evt.data.view.hide() ;
		}) ;
	}
}) ;


MyVCFApp.Form = $.inherit(MyVCFApp.View, {
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppForm' ;
		this.__base(props) ;
		if (!this.url) this.url = '' ;
		if (!this.fields) this.fields = [] ;
		if (!this.onBeforeSubmit) this.onBeforeSubmit = null ;
		if (!this.onSubmit) this.onSubmit = null ;
		this.xtype = 'form' ;
	},
	_generateEvents: function() {
		this.__base() ;
		this.searchAllFields() ;
	},
	searchAllFields: function() {
		var res = this.findByXType('textfield') ;
		for(var i=0 ; i<res.length ; i++) {
			this.addField(res[i]) ;
		}
		var res = this.findByXType('selectfield') ;
		for(var i=0 ; i<res.length ; i++) {
			this.addField(res[i]) ;
		}
		var res = this.findByXType('textarea') ;
		for(var i=0 ; i<res.length ; i++) {
			this.addField(res[i]) ;
		}
		var res = this.findByXType('field') ;
		for(var i=0 ; i<res.length ; i++) {
			this.addField(res[i]) ;
		}
	},
	addField: function(field) {
		this.fields.push(field) ;
	},
	reset: function() {
		for(var i=0 ; i<this.fields.length ; i++) {
			this.fields[i].reset() ;
		}
	},
	submit: function(data) {
		var dataToSend = this.getEl().serializeArray() ;
		for(var i=0 ; i<dataToSend.length ; i++) {
			var v = this.findFieldByName(dataToSend[i].name) ;
			if (v) {
				if (v.getValue()==v.emptyText) {
					dataToSend[i].value = '' ;
					log("trouve", dataToSend[i].name) ;
				}
			}
		}
		if (data) {
			var dPlus = [] ;
			for(key in data) {
				dPlus.push({name:key, value:data[key]}) ;
			}
			dataToSend = $.merge(dataToSend, dPlus) ;
		}
		//log("dataToSend", dataToSend) ;
		if (this.onBeforeHide && !this.onBeforeHide()) return ;
		$.ajax({
			type: 'POST',
			url: this.url,
			data: dataToSend,
			context: this,
			dataType: 'json',
			success: function() {
				if (this.onSubmit) this.onSubmit.apply(this.scope, arguments) ;
			}
		});
	},
	load: function() {
	},
	loadData: function(data) {
		
	},
	_generate: function() {
		var txt = "" ;
		txt += "<form style='"+this.style+"' class='"+this.cls+"' id='"+this.id+"' action='#' method='POST'>" ;
		txt += this.__base() ;
		txt += "</form>" ;
		return txt ;
	}
}) ;

MyVCFApp.Field = $.inherit(MyVCFApp.View, {
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppField' ;
		this.__base(props) ;
		if (!this.width) this.width = 200 ;
		if (!this.name) this.name = '' ;
		if (!this.value) this.value = '' ;
		if (!this.emptyText) this.emptyText = null ;
		else this.value = this.emptyText ;
		this.xtype = 'field' ;
	},
	reset: function() {
		this.setValue('') ;
	},
	setValue: function(value) {
		this.value = value ;
		this.getEl().val(value) ;
		if (this.emptyText && value=='') this.getEl().val(this.emptyText) ;
	},
	getValue: function() {
		return this.getEl().val() ;
		//return this.value ;
	}
}) ;

MyVCFApp.TextField = $.inherit(MyVCFApp.Field, {
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppTextField' ;
		this.__base(props) ;
		this.xtype = 'textfield' ;
	},
	_generate: function() {
		var txt = "" ;
		txt += "<div><input style='"+this.style+"' class='"+this.cls+"' type='text' id='"+this.id+"' name='"+this.name+"' value=\""+this.value+"\" /></div>" ;
		return txt ;
	},
	_generateEvents: function() {
		this.__base() ;
		$("#"+this.id).focusin({view:this}, function(evt) {
			var this2 = evt.data.view ;
			//var this2 = this ;
			//log(this2) ;
			var jqEl = this2.getEl() ;
			if (this2.emptyText && jqEl.val()==this2.emptyText) jqEl.val('') ;
		}) ;
		$("#"+this.id).focusout({view:this}, function(evt) {
			var this2 = evt.data.view ;
			var jqEl = this2.getEl() ;
			if (this2.emptyText && jqEl.val()=='') jqEl.val(this2.emptyText) ;
		}) ;
	}
}) ;
MyVCFApp.TextArea = $.inherit(MyVCFApp.TextField, {
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppTextArea' ;
		this.__base(props) ;
		this.xtype = 'textarea' ;
	},
	_generate: function() {
		var txt = "" ;
		txt += "<div><textarea style='"+this.style+"' class='"+this.cls+"' id='"+this.id+"' name='"+this.name+"'>"+this.value+"</textarea></div>" ;
		return txt ;
	}
}) ;

MyVCFApp.SelectField = $.inherit(MyVCFApp.Field, {
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppSelectField' ;
		this.__base(props) ;
		if (!this.selectOptions) this.selectOptions = [] ;
		this.xtype = 'selectfield' ;
	},
	_generate: function() {
		var txt = "" ;
		txt += "<div><select style='"+this.style+"' class='"+this.cls+"' id='"+this.id+"' name='"+this.name+"'>" ;
		log("this.selectOptions",this.selectOptions) ;
		for(var i=0 ; i<this.selectOptions.length ; i++) {
			txt += "<option value='"+this.selectOptions[i][0]+"'>"+this.selectOptions[i][1]+"</option>" ;
		}
		txt += "</select></div>" ;
		return txt ;
	},
	_generateEvents: function() {
		this.__base() ;
		$("#"+this.id).focusin({view:this}, function(evt) {
			var this2 = evt.data.view ;
			//var this2 = this ;
			//log(this2) ;
			var jqEl = this2.getEl() ;
			if (this2.emptyText && jqEl.val()==this2.emptyText) jqEl.val('') ;
		}) ;
		$("#"+this.id).focusout({view:this}, function(evt) {
			var this2 = evt.data.view ;
			var jqEl = this2.getEl() ;
			if (this2.emptyText && jqEl.val()=='') jqEl.val(this2.emptyText) ;
		}) ;
	},
	reset: function() {
		this.setValue(1) ;
	}
}) ;


MyVCFApp.BrowseField = $.inherit(MyVCFApp.Field, {
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppBrowseField' ;
		this.__base(props) ;
		this.xtype = 'browsefield' ;
	},
	_generate: function() {
		var txt = "" ;
		txt += "<div><input style='"+this.style+"' class='"+this.cls+"' type='file' id='"+this.id+"' name='"+this.name+"' value=\""+this.value+"\" /></div>" ;
		return txt ;
	},
	_generateEvents: function() {
		this.__base() ;
	}
}) ;

MyVCFApp.HiddenField = $.inherit(MyVCFApp.Field, {
	__constructor: function(props) {
		if (!props.cls) props.cls = 'MyVCFAppHiddenField' ;
		this.__base(props) ;
		this.xtype = 'hiddenfield' ;
	},
	_generate: function() {
		var txt = "" ;
		txt += "<div><input class='"+this.cls+"' type='hidden' id='"+this.id+"' name='"+this.name+"' value=\""+this.value+"\" /></div>" ;
		return txt ;
	},
	_generateEvents: function() {
		this.__base() ;
	}
}) ;







