var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDevReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDevReady: function() {
        app.DoDeviceReady('deviceready');
    },
    // Update DOM on a Received Event
    DoDeviceReady: function(id) {
        //triggerAlert('Titlu alerta','mesaj alerta');
		startWhenDeviceIsReady();
    }
    
};



//document.addEventListener("deviceready", onDeviceReady, false);

var isCurrentSession = '';
var ThePassword = '';
var entryList = new Array();
var backgroudImage = '';

var currentTime = new Date();
var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

//localStorage.isCurrentSession = "FALSE";
//localStorage.ThePassword = ''

function loadjscssfile(filename, filetype){
	 if (filetype=="js"){ //if filename is a external JavaScript file
		  var fileref=document.createElement('script');
		  fileref.setAttribute("type","text/javascript");
		  fileref.setAttribute("src", filename);
	 }
	 else if (filetype=="css"){ //if filename is an external CSS file
		  var fileref=document.createElement("link");
		  fileref.setAttribute("rel", "stylesheet");
		  fileref.setAttribute("type", "text/css");
		  fileref.setAttribute("href", filename);
	 }
	 if (typeof fileref!="undefined"){
	 	document.getElementsByTagName("head")[0].appendChild(fileref);
	 }
}

function startWhenDeviceIsReady() {
							
	if (localStorage.getItem('isCurrentSession') !== undefined &&  localStorage.getItem('isCurrentSession') == 'TRUE' ){	
				
		if (localStorage.getItem('backgroudImage') !== undefined &&  localStorage.getItem('backgroudImage') != '' && localStorage.getItem('backgroudImage') != null){
			$('#thebody').css('background-image','url(img/'+localStorage.getItem('backgroudImage')+'.png)');		
		}else{
			$('#thebody').css('background-image','url(img/back.png)');			
		}	
		
		
		$('#startscreen').hide();				
		getEntries(monthNames[currentTime.getMonth()],currentTime.getFullYear());
		$('#entireframe').show();
		
	}else{
		isCurrentSession = '';
		$('#thebody').css('background-image','url(img/xv.png)');		
		if (localStorage.getItem('ThePassword')!== undefined && localStorage.getItem('ThePassword') !=''&& localStorage.getItem('ThePassword') !=null){			
			$('#loginform').show();
			$('#registerform').hide();
		}else{			
			$('#registerform').show();
			$('#loginform').hide();
		}
	}
}



function triggerAlert(title, message){
   /* navigator.notification.alert(
                                 message,
                                 callBackFunctionB, // Specify a function to be called
                                 title,
                                 "OK"
                                 );*/
								 
	alert(message);
}

function callBackFunctionB(){
    //do nothing
}
var perw = new Date();
function setPeriodw(){
	$('#writedate_day').val(dateFormat(perw, "dd"));
	$('#writedate_mon').val(dateFormat(perw, "mmm"));              
	$('#writedate_year').val(dateFormat(perw, "yyyy"));
}

function addDayw(){	
	perw.setDate(perw.getDate() + 1);	
	updateperiodw();
}

function addMonthw(){	
	perw.setMonth(perw.getMonth() + 1);
	updateperiodw();
}

function addYearw(){	
	perw.setYear(perw.getFullYear() + 1);
	updateperiodw();
}

function reduceDayw(){	
	perw.setDate(perw.getDate() - 1);	
	updateperiodw();
}

function reduceMonthw(){	
	perw.setMonth(perw.getMonth() - 1);
	updateperiodw();
}

function reduceYearw(){	
	perw.setYear(perw.getFullYear() - 1);
	updateperiodw();
}

function updateperiodw() {
	$('#writedate_day').val(dateFormat(perw, "dd"));
	$('#writedate_mon').val(dateFormat(perw, "mmm"));      
	$('#writedate_year').val(dateFormat(perw, "yyyy"));
            
}


var per = new Date();     
function setPeriod(){	         
	$('#monthpick_mon').val(dateFormat(per, "mmm"));              
	$('#monthpick_year').val(dateFormat(per, "yyyy"));
}
function addMonth(){	
	per.setMonth(per.getMonth() + 1);
	updateperiod();
}

function addYear(){	
	per.setYear(per.getFullYear() + 1);
	updateperiod();
}

function reduceMonth(){	
	per.setMonth(per.getMonth() - 1);
	updateperiod();
}

function reduceYear(){	
	per.setYear(per.getFullYear() - 1);
	updateperiod();
}

function updateperiod() {
  $('#monthpick_year').val(dateFormat(per, "yyyy"));
  $('#monthpick_mon').val(dateFormat(per, "mmm"));                 
}




//function onDeviceReady() {
//	document.addEventListener("backbutton", function(e){
//           e.preventDefault();
//           navigator.app.exitApp();
//		   CloseSession();
//    }, false);
//	CloseSession();
//}



function Login(){
	
	if($('#loginpassword').val() == localStorage.getItem('ThePassword') ){ 		
		localStorage.setItem('isCurrentSession','TRUE');
		if (localStorage.getItem('backgroudImage') !== undefined &&  localStorage.getItem('backgroudImage') != '' &&  localStorage.getItem('backgroudImage') != null ){
			$('#thebody').css('background-image','url(img/'+localStorage.getItem('backgroudImage')+'.png)');
		}else{
			$('#thebody').css('background-image','url(img/back.png)');
		}
		$('#startscreen').hide();			
		$('#loginpassword').val('');
		getEntries(monthNames[currentTime.getMonth()],currentTime.getFullYear());
		$('#entireframe').show();
	}else{
 		triggerAlert('Authentication problem', 'Invalid password!');
	}
}

function closeApp(){
	 LogOutAndClose();	 
}

function CloseSession(){
	localStorage.setItem('isCurrentSession','FALSE') ;
	$('#thebody').css('background-image','url(img/xv.png)');
	$('#startscreen').show();			
	if (localStorage.getItem('ThePassword') !== undefined && localStorage.getItem('ThePassword')!= ''&& localStorage.getItem('ThePassword')!= null){		
		$('#loginform').show();
	}
	$('#entireframe').hide();
	
}

function LogOutAndClose(){
	localStorage.setItem('isCurrentSession','FALSE');
	$('#thebody').css('background-image','url(img/xv.png)');
	$('#startscreen').show();		
	$('#loginform').show();
	$('#entireframe').hide();	
	//navigator.app.exitApp();
}

function LoginRegister(){
	
	if($('#registerpassword').val() != '' && $('#confirmregisterpassword').val() != ''){
		if($('#registerpassword').val() == $('#confirmregisterpassword').val()){ 
			localStorage.setItem('ThePassword',$('#registerpassword').val());
			localStorage.setItem('isCurrentSession', 'TRUE');
			$('#thebody').css('background-image','url(img/back.png)');
			$('#startscreen').hide();			
			getEntries(monthNames[currentTime.getMonth()],currentTime.getFullYear());
			$('#entireframe').show();
			$('#registerform').hide();
		}else{
			triggerAlert('No match','Passwords do not match. Password and cofirmed password must match.')
		}
	}else{
		triggerAlert('Missing values','Both Password and Confirmation password fields need to be filled. Try again.');
	}	
}

function EditEntry(date,page){
	if (page != "viewentry"){
		date = $("#writedate_day").val()+"-"+$("#writedate_mon").val()+"-"+$("#writedate_year").val();
	}	
	$.mobile.changePage("#editentry",{ transition: "none"},true, true);
	$("#editentryback").attr("href", "#"+page)
	$("#editentrydate").html(date);
	$("#selDate").val(date);
	
	if(localStorage.getItem('lista')!== undefined && localStorage.getItem('lista') != null){
		var stringObject = localStorage.getItem('lista');
		var objList = JSON.parse(localStorage.getItem('lista'));
		
		var title = '';				
		var description = '';
		$.each(objList.myarray, function(i,item){	
			
			if (item.date == date){
				title = item.title,
				description = item.description				
			}
		});
		$("#title").val(title);
		$("#details").val(description);
		
	}else{
		$("#title").val('');
		$("#details").val('');
	}
	
	
}

function ViewEntry(date){
	$.mobile.changePage("#viewentry",{ transition: "none"},true, true);
	
	var title = '';				
	var description = '';
	if(localStorage.getItem('lista')!== undefined && localStorage.getItem('lista') != null){
		var stringObject = localStorage.getItem('lista');
		var objList = JSON.parse(localStorage.getItem('lista'));
		$.each(objList.myarray, function(i,item){				
			if (item.date == date){
				title = item.title,
				description = item.description				
			}
		});		
	}	
	$('#veziEntry').html('<div id="capsa" class="capsa" ></div><div id="capsa1" class="capsa1" ></div><a  onClick="javascript:EditEntry(\''+date+'\',\'viewentry\');" style="decoration:none"><div class="olinie" ><table cellspacing="2" width="100%"><tr><td valign="middle" width="55px"><img src="img/calendar.png" /></td><td ><span style="font-family: \'Courgette\', cursive; font-size:20px; font-weight:500;">'+date+'</span><div style="color:#828; font-size:11px; padding-top:4px; font-family: \'Courgette\', cursive;">(Tap to edit)</div></td><td width="20px;" valign="middle"><img src="img/arrow.png"/></td></tr><tr><td colspan="3" style="border-top:1px dashed #DDD; padding-top:5px;"><div style="color:#828;font-size:16px; font-family: \'Courgette\', cursive; padding:10px;">"'+title+'"</div></td></tr></table></div> <div class="olinie" ><table cellspacing="2" width="100%"><tr><td colspan="3" style=" padding-top:3px; padding-bottom:6px;"><div style="color:#222;font-size:14px; font-family: \'Courgette\', cursive;">"'+description+'"</div></td></tr></table></div></a>');
}

function SaveEntry(){
	//save entry	
	if( $('#title').val() != '' && $('#details').val() != ''){
		if ($('#selDate').val() != ''){
			
			var date = $('#selDate').val();	
			var month = date.split('-')[1];
			var extYear = date.split('-')[2];
			
			
			if(localStorage.getItem('lista')!== undefined && localStorage.getItem('lista') != null){
				var stringObject = localStorage.getItem('lista');
				var objList = JSON.parse(localStorage.getItem('lista'));
				
				var myarray = [];				
				$.each(objList.myarray, function(i,item){					
					var item = {
						"month": item.month,
						"date": item.date,
						"title": item.title,
						"description": item.description
					};
					myarray.push(item);					
				});
				
				
				if (myarray.length > 0){					
					var myJSON = "";
					var afost = 0;
					for (var ii = 0; ii < myarray.length; ii++){						
						if(myarray[ii]['date'] == date){
							
							myarray[ii]['month'] = month;
							myarray[ii]['date'] = date;
							myarray[ii]['title'] = $('#title').val();
							myarray[ii]['description'] = $('#details').val();
							
							afost = 1;
						}
					}
					if (afost == 0){
							var item = {
								"month": month,
								"date": date,
								"title": $('#title').val(),
								"description": $('#details').val()
							};
							myarray.push(item);
					}					
					myJSON = JSON.stringify({myarray: myarray});
					localStorage.setItem('lista',myJSON);
				}else{
					
					var myarray = [];
					var myJSON = "";
					var item = {
						"month": month,
						"date": date,
						"title": $('#title').val(),
						"description": $('#details').val()
					};
					
					myarray.push(item);
					myJSON = JSON.stringify({myarray: myarray});
					localStorage.setItem('lista',myJSON);
				}				
			}else{
				
				var myarray = [];
				var myJSON = "";
				var item = {
					"month": month,
					"date": date,
					"title": $('#title').val(),
					"description": $('#details').val()
				};
				
				myarray.push(item);
				myJSON = JSON.stringify({myarray: myarray});
				localStorage.setItem('lista',myJSON);
			}
			
			triggerAlert('Success','Entry added successfully!');
			
			$('#title').val('');
			$('#details').val('');
			getEntries(month,extYear);
			
		}else{
			
			//missing the date
		}		
	}else{
		triggerAlert('Missing info','Both Title and Details fields need to be filled.')
	}
}

function getEntries(month,year){
	$.mobile.changePage("#mainpage",{ transition: "none"},true, true);
	
	if(localStorage.getItem('lista')!== undefined && localStorage.getItem('lista') != null){
		var stringObject = localStorage.getItem('lista');
		var objList = JSON.parse(localStorage.getItem('lista'));
		
		var myarray = [];				
		$.each(objList.myarray, function(i,item){	
			var extyear = item.date.split('-')[2];
			if (item.month == month && extyear == year){
				var item = {
					"month": item.month,
					"date": item.date,
					"title": item.title,
					"description": item.description
				};
				myarray.push(item);	
			}
		});
		if (myarray.length == 0){
			$('#entrybox').html('<div id="capsa" class="capsa" ></div><div id="capsa1" class="capsa1" ></div><div class="olinie" style="display:nonel" id="noentries" ><table cellspacing="2" width="100%"><tr><td valign="middle" width="5px"></td><td style="padding-bottom:10px;"><span style="font-family: \'Courgette\', cursive; font-size:16px; font-weight:500;">No entries yet for selected month. You can start writing by tapping the pen icon on the bottom of the screen</span></td><td width="0px;" valign="middle"></td></tr></table></div>');
		}else{
			$('#entrybox').html('');
		
			var html = '';
			
			//sort array
			myarray.sort(function(a,b) {
			  return parseInt(a.date,10) - parseInt(b.date,10);			
			});

			
			for (var i=0; i<myarray.length; i++ ){
				var title = myarray[i]['title'];
				var description = myarray[i]['description'];
				
				if (title.length > 60){
					title = title.substring(0,57)+' ...';
				}
				
				if (description.length > 100){
					description = description.substring(0,97)+' ...';
				}
				
				html = html + '<div id="capsa" class="capsa" ></div><div id="capsa1" class="capsa1" ></div><a onClick="javascript:ViewEntry(\''+myarray[i]['date']+'\');" style="text-decoration:none"><div class="olinie"><table cellspacing="2" width="100%"><tr><td valign="middle" width="55px"><img src="img/calendar.png" /></td><td ><span style="font-family: \'Courgette\', cursive; font-size:18px; font-weight:500;">'+myarray[i]['date']+'</span><div style="color:#828; font-size:16px; padding-top:4px; font-family: \'Courgette\', cursive;">"'+title+'"</div></td><td width="20px;" valign="middle"><img src="img/arrow.png"/></td></tr><tr><td colspan="3" style="border-top:1px dashed #DDD; padding-top:5px;"><div style="color:#222;font-size:14px; font-family: \'Courgette\', cursive;">"'+description+'"</div></td></tr></table> </div></a> ';
			}
			
			$('#entrybox').html(html);
		}
	}else{
		$('#entrybox').html('<div id="capsa" class="capsa" ></div><div id="capsa1" class="capsa1" ></div><div class="olinie" style="display:nonel" id="noentries" ><table cellspacing="2" width="100%"><tr><td valign="middle" width="5px"></td><td style="padding-bottom:10px;"><span style="font-family: \'Courgette\', cursive; font-size:16px; font-weight:500;">No entries yet for selected month. You can start writing by tapping the pen icon on the bottom of the screen</span></td><td width="0px;" valign="middle"></td></tr></table></div>');
	}
}



function Settings(page){	
	$.mobile.changePage("#settings",{ transition: "none"},true, true);
	$("#settingsback").attr("href", "#"+page)
}


function SetMonth(){
	if ($('#monthpick_mon').val() != '' && $('#monthpick_year').val() != ''){
		getEntries($('#monthpick_mon').val(),$('#monthpick_year').val());
	}
}


function SaveNewPassword(){
	if($('#oldpassword').val() != '' && $('#newpassword').val() != '' && $('#confirmpassword').val() != ''){
		if($('#newpassword').val() == $('#confirmpassword').val()){ 
			if($('#oldpassword').val() == localStorage.getItem('ThePassword')){
				localStorage.setItem('ThePassword',$('#newpassword').val());
				$('#oldpassword').val('');
				$('#newpassword').val('');
				$('#confirmpassword').val('');
				triggerAlert('Success','Your password was updated sucessfully. Thank you!')
			}else{
				triggerAlert('Invalid password','Invalid old password. Try again later.')
			}
		}else{
			triggerAlert('No match','Passwords do not match. New password and cofirmed new password must match.');
		}
	}else{
		triggerAlert('Missing fields','All fields are mandatory.');
	}	
}

function PickMonth(){
	$.mobile.changePage("#pickmonth",{ transition: "none"},true, true);	
	setPeriod();
}

function NewWrite(){
	$.mobile.changePage("#choosewritedate",{ transition: "none"},true, true);	
	setPeriodw();
}

////////////////////////
//ajax calls
////////////////////////



        
function checkIfEmailExist(email){
	var theReturn = 0;	
	
	var URL = 'http://secretdiary.berce.biz/data.php?action=verifyexists';
	var params = 'EMAIL='+email;
	var followfunc = 'processCheckEmailExist';
	var SEmail = email;
	var SPassword = '';	
	callServer(URL,params,SEmail,SPassword,followfunc);
	
}
function processCheckEmailExist(data,email){
    
    if(data.status == 'Email allready exists'){
        localStorage.setItem('EmailS',email);
        serverSave();
        
    }else{
        if(email != ''){
            localStorage.setItem('tempEmailS',email);
        }
        serverSave();
    }
}


function saveEmailWithPassword(email, password){
	
	$.jsonp({url: 'http://secretdiary.berce.biz/data1.php?action=createaccount&EMAIL='+email+'&PASSWORD='+password+'&callback=?',
                    timeout: 25000,
                    success: function(data) {						
                         processSaveEmailWithPassword(data, email, password);
                    },
                    error: function(){
                        triggerAlert('Internet Access','A problem ocurred during the load. Internet access is required!');
                    }
                });
				
	/*$.post("http://secretdiary.berce.biz/data.php?action=createaccount",{'EMAIL':email,'PASSWORD':password},function(data){           
           processSaveEmailWithPassword(data, email, password);
	});*/
		
}
function processSaveEmailWithPassword(data,email,password){
    if(data.status == 'Account created'){
        triggerAlert('Success','Email and password successfuly saved!');
        localStorage.setItem('EmailS',email);
        $('#emailpass').val(password);
        serverSave();
    }else{
        
    }
}



function saveDataOnServer(email,password,theData){      
	if (email != '' && password != ''){        
	
		var URL = 'http://secretdiary.berce.biz/data.php?action=savedata';
		var params = 'EMAIL='+email+'&PASSWORD='+password+'&DATA='+theData;
		var followfunc = 'afterSave';
		var SEmail = email;
		var SPassword = password;	
		callServer(URL,params,SEmail,SPassword,followfunc);		
		
		/*$.post("http://secretdiary.berce.biz/data.php?action=savedata",{'EMAIL':email,'PASSWORD':password,'DATA':theData},function(data){
               afterSave(data);
		});*/
	}else{
		triggerAlert('Error','Missing email or password. Please fill in all the fields');		
	}
}

function afterSave(data){
    var perw = new Date();
    var month = dateFormat(perw, "mmm");
    var extYear = dateFormat(perw, "yyyy");
    
    if(data.status == 'Data successfully saved'){
        triggerAlert('Success!','Your data was successfully saved & syncronized.');
        getEntries(month,extYear);
    }else if (data2.status == 'Incorrect login information') {
        triggerAlert('Login failed','Incorrect login information, incorect password or email');
        
    }else{
        triggerAlert('Error','An error ocurred. Please try again later. Internet connection is needed.');
        
    }
}

function getDataFromServer(email, password){
	if (email != '' && password != ''){	
		
		var URL = 'http://secretdiary.berce.biz/data.php?action=getdata';
		var params = 'EMAIL='+email+'&PASSWORD='+password;
		var followfunc = 'processSaveServerDataExistance';
		var SEmail = email;
		var SPassword = password;	
		callServer(URL,params,SEmail,SPassword,followfunc);	
		
		/*$.post("http://secretdiary.berce.biz/data.php?action=getdata",{'EMAIL':email,'PASSWORD':password},function(data){
               processSaveServerDataExistance(email,password,data);
		});*/
	}else{
		triggerAlert('Error','Missing email or password. Please fill in all the fields');
	}
	
}

function callServer(URL,params,email,password,followfunc){						
	//URL = "http://secretdiary.berce.biz/data2.php?action=verifyexists";
	//var url = "ceva.html";                        
	
	//var url = listacanale[numeprogram]['urlprogram'];
	//url = url.replace('DATA_PROGRAMULUI',ziua);	
	
	var req = new XMLHttpRequest();
	req.open("POST", URL, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.setRequestHeader("Content-length", params.length);
    req.setRequestHeader("Connection", "close");
	req.onreadystatechange = function onResult(){
			if (this.readyState == 4){			
				loadResult(this.responseText,email,password,followfunc);			
			}else{
				//$('#theloader').hide();
			}		
		};
	req.send(params);
}
                    
function loadResult(data,email,password,followfunc){
	var objList = JSON.parse(data);
	if(followfunc == 'processCheckEmailExist'){		
		processCheckEmailExist(objList,email);
	}	
	if(followfunc == 'afterSave'){		
		afterSave(objList);
	}	
	if(followfunc == 'processSaveServerDataExistance'){		
		processSaveServerDataExistance(email, password, objList);
	}
	if(followfunc == 'prepareDeleteAccount'){		
		prepareDeleteAccount(objList);
	}
}

function delVerifyAccount(email, password){
	var theReturn = 0;
	var URL = 'http://secretdiary.berce.biz/data.php?action=verifydelete';
	var params = 'EMAIL='+email+'&PASSWORD='+password;
	var followfunc = 'prepareDeleteAccount';
	var SEmail = email;
	var SPassword = password;	
	callServer(URL,params,SEmail,SPassword,followfunc);	
	
	/*$.post("http://secretdiary.berce.biz/data.php?action=verifydelete",{'EMAIL':email,'PASSWORD':password},function(data){
           prepareDeleteAccount(data);
	});*/	
}
function prepareDeleteAccount(data){
    if(data.status == 'Email allready exists'){        
        doRemoveEmailAddress();
    }else{        
        triggerAlert('Invalid password','Invalid password, try again later.');
    }
}
function doRemoveEmailAddress(){
    triggerAlert('Success','Email and password information removed.');
    localStorage.setItem('tempEmailS','');
    localStorage.setItem('EmailS', '');
    serverSave();
}


/////////////////////////
//updates
/////////////////////////

function processSaveServerDataExistance(email,password,data){
    var consolidatedData = '';
    var consolidatedArray = [];
    var serverArray = [];
    var myarray = [];
    
    if(data.status == 'Data returned'){
         
		var serverStringObject = data;
        
        var passlevel = 0;
        if (serverStringObject.data == ''){            
            passlevel = 1;
        }else{
            passlevel = 2;
        }
        
        
        if (passlevel == 1){            
			consolidatedData = localStorage.getItem('lista');
		}else{            
			var serverObjList = JSON.parse(serverStringObject.data);
			
            //serverArray
			$.each(serverObjList.myarray, function(i,item){
                   var item = {
                        "month": item.month,
                        "date": item.date,
                        "title": item.title,
                        "description": item.description
                   };
                   serverArray.push(item);
            });
            
			
			var objList = JSON.parse(localStorage.getItem('lista'));
            
			
            if(localStorage.getItem('lista')!== undefined && localStorage.getItem('lista') != null){
                //myarray
               
                $.each(objList.myarray, function(i,item){
                    var item = {
                       "month": item.month,
                       "date": item.date,
                       "title": item.title,
                       "description": item.description
                       };
                       myarray.push(item);
                });
                
			
                for (var i1 = 0; i1 < myarray.length; i1++){
                    var tmonth = myarray[i1]['month'];
                    var tdate = myarray[i1]['date'];
                    var ttitle = myarray[i1]['title'];
                    var tdescription = myarray[i1]['description'];
				
                    for (var i2 = 0; i2< serverArray.length; i2++){
                        if (myarray[i1]['date'] == serverArray[i2]['date']){
                            //merge title
                            if (myarray[i1]['title'] != serverArray[i2]['title']){
                                
                                if(myarray[i1]['title'].length > serverArray[i2]['title'].length){
                                    if(myarray[i1]['title'].search(serverArray[i2]['title']) >=0 ){
                                        serverArray[i2]['title'] = 'assus!@#$';
                                    }else{
                                        ttitle = ttitle + ' <->SYNC<-> ' + serverArray[i2]['title'];
                                        serverArray[i2]['title'] = 'assus!@#$';
                                    }                                    
                                }else{
                                    if(serverArray[i2]['title'].search(myarray[i1]['title']) >=0 ){
                                        ttitle = serverArray[i2]['title'];
                                        serverArray[i2]['title'] = 'assus!@#$';
                                    }else{
                                        ttitle = ttitle + ' <->SYNC<-> ' + serverArray[i2]['title'];
                                        serverArray[i2]['title'] = 'assus!@#$';
                                    }                                    
                                }
                            }else{
                                serverArray[i2]['title'] = 'assus!@#$';
                            }
						
                            //merge description
                            if (myarray[i1]['description'] != serverArray[i2]['description']){
                                
                                if(myarray[i1]['description'].length > serverArray[i2]['description'].length){
                                    if(myarray[i1]['description'].search(serverArray[i2]['description']) >=0 ){                                        
                                    }else{
                                        tdescription = tdescription + ' <->SYNC<-> ' + serverArray[i2]['description'];                                        
                                    }
                                }else{
                                    if(serverArray[i2]['description'].search(myarray[i1]['description']) >=0 ){
                                        tdescription = serverArray[i2]['description'];                                        
                                    }else{
                                        tdescription = tdescription + ' <->SYNC<-> ' + serverArray[i2]['description'];
                                    }
                                }
                            }
                        }
                    }
				
                    consolidatedArray.push({
                                       "month": tmonth,
                                       "date": tdate,
                                       "title": ttitle,
                                       "description": tdescription
                                       });
                }
            }
            
			
			for (var i3 = 0; i3 < serverArray.length; i3++){
				if (serverArray[i3]['title'] != 'assus!@#$'){
					consolidatedArray.push({
                                           "month": serverArray[i3]['month'],
                                           "date": serverArray[i3]['date'],
                                           "title": serverArray[i3]['title'],
                                           "description": serverArray[i3]['description']
                                           });
				}
			}
            
            myarray = consolidatedArray;
			
			myJSON = JSON.stringify({ myarray :myarray});            
			consolidatedData = myJSON;            
			localStorage.setItem('lista',myJSON);
		}
		if(consolidatedData != '' && consolidatedData != 'null' && consolidatedData != null){
            saveDataOnServer(email,password,consolidatedData);
        }else{
            triggerAlert('No data','No data for syncronization')
        }
    }else if (data.status == 'Incorrect login information') {
        triggerAlert('Login failed','Incorrect login information, incorect password or email');
        
    }else{
        triggerAlert('Error','An error ocurred. Please try again later. Internet connection is needed.');
        
    }
	
	$('#emailpass').val('');
    
}

function saveServerDataExistance(){
	var curPassword = $('#emailpass').val();	
	if (curPassword != '' && localStorage.getItem('EmailS') !=''&& localStorage.getItem('EmailS') !=null){
        
        $.jsonp({
                url: 'http://secretdiary.berce.biz/testcon.php?action=verifyexists'+'&callback=?',
                timeout: 25000,
                success: function() {
                    getDataFromServer(localStorage.getItem('EmailS'),curPassword);	
                },
                error: function(){
                    triggerAlert('Internet Access','A problem ocurred during the load. Internet access is required!');
                }
        });
			
	}else{
		triggerAlert('Missing data','Missing email or/and password. Please fill in all fields!');
	}
	
}


function removeEmailAddress(){
    $.jsonp({
            url: 'http://secretdiary.berce.biz/testcon.php?action=verifyexists'+'&callback=?',
            timeout: 25000,
            success: function() {
                delVerifyAccount(localStorage.getItem('EmailS'),$('#emailpass').val());
            },
            error: function(){
                triggerAlert('Internet Access','A problem ocurred during the load. Internet access is required!');
            }
    });
	
}

function saveEmailPasswordExistance(){
	var pass1 = '';
	var pass2 = '';
	var emailAndPasswordSaved = 0;
	pass1 = $('#emailcpass1').val();
	pass2 = $('#emailcpass2').val();
	if(pass1 != '' && pass2 != ''){
		if (pass1 == pass2){
			if(localStorage.getItem('tempEmailS') != ''){
                $.jsonp({
                        url: 'http://secretdiary.berce.biz/testcon.php?action=verifyexists'+'&callback=?',
                        timeout: 25000,
                        success: function() {
                            saveEmailWithPassword(localStorage.getItem('tempEmailS'), pass1);
                        },
                        error: function(){
                            triggerAlert('Internet Access','A problem ocurred during the load. Internet access is required!');
                        }
                });
                
			}else{triggerAlert('Missing email','Missing email address!');}
		}else{
			triggerAlert('Invalid password','Password and confirm password need to be the same.');
		}
	}else{
		triggerAlert('Missing values','You need to fill in both password and confirm password.');
	}
	
}

function checkEmailExistance(){
	var temail = '';
	var theEmailExists = 0;
	
	temail = $('#email').val();
    if(validateEmail(temail) == true){		
        if(temail != ''){
            $.jsonp({
                    url: 'http://secretdiary.berce.biz/testcon.php?action=verifyexists'+'&callback=?',
                    timeout: 25000,
                    success: function() {						
                        checkIfEmailExist(temail);
                    },
                    error: function(){
                        triggerAlert('Internet Access','A problem ocurred during the load. Internet access is required!');
                    }
                });
		
        }else{
            triggerAlert('Missing email','You need to fill in a valid email address');
        }
    }else{
        triggerAlert('Invalid email','Invalid email address. Please fill in a valid email address.');
    }
}

////////////////////////////////
//update server settings screen
////////////////////////////////

function serverSave(){
    
	$.mobile.changePage("#serversave",{ transition: "none"},true, true);
	
	$('#emailexists').hide();
	$('#email').hide();
	$('#semailcpass1').hide();
	$('#emailcpass1').hide();
	$('#semailcpass2').hide();
	$('#emailcpass2').hide();
	$('#semailpassword').hide();
	$('#emailpass').hide();
	$('#seversavepassword').hide();
	$('#serversavedata').hide();
	$('#removeemailaddress').hide();
	$('#servercontinue').hide();
	
	
	
	if (localStorage.getItem('EmailS') !== undefined && localStorage.getItem('EmailS') != ''&& localStorage.getItem('EmailS') != null){
		
		$('#emailexists').show(); $('#emailexists').html(localStorage.getItem('EmailS'));
		$('#semailpassword').show();
		$('#emailpass').show();
		$('#serversavedata').show();
		$('#removeemailaddress').show();
		
	}else if (localStorage.getItem('tempEmailS') !== undefined && localStorage.getItem('tempEmailS') != ''&& localStorage.getItem('tempEmailS') != null){
		$('#emailexists').show(); $('#emailexists').html(localStorage.getItem('tempEmailS'));
		$('#semailcpass1').show();
		$('#emailcpass1').show();
		$('#semailcpass2').show();
		$('#emailcpass2').show();
		$('#seversavepassword').show();
	}else{
		$('#email').show();
		$('#servercontinue').show();
	}
}


////////////////////////////////
//lookandfeel
////////////////////////////////
function lookAndFeel(){    
	$.mobile.changePage("#lookandfeel",{ transition: "none"},true, true);
}
function changeBackgroud(image){
	
	localStorage.setItem('backgroudImage',image);
	$('#thebody').css('background-image','url(img/'+image+'.png)');
}

function changeFont(fileName){
	localStorage.setItem('cssFile',fileName);    
	loadjscssfile(fileName,'css');    
    triggerAlert('Success','All your changes where successfully saved.');
	
}

/////////////////////////////////
/////utilities
////////////////////////////////

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}



