var DialogInviteLoading = null;
var DialogInviteForm = null;
var DialogInviteSending = null;
var DialogInviteComplete = null;
/* translation */
var trans_enter_login = 'Please enter your username!';
var trans_enter_password = 'Please enter your password!';
var trans_email_format = 'Wrong email address format.';
var trans_enter_email = 'Please specify email address.';
var trans_enter_name = 'Please specify your name.';
var trans_enter_your_email = 'Please specify email address.';
var trans_enter_text = 'Please type your text';
var trans_incor_uname_passwd = 'UserName or Password is incorrect.';



var iv_ssid = null;
var iv_key = null;
var member = true;

function AlbumInvite() {
	advAJAX.post({
		"cmd"		 : "invite_album",
      evalScripts: true,
	onLoading: function(obj) {
		if (!DialogInviteForm) {
			DialogInviteForm = new ModalDialog('album_invite_form');
		}
		DialogInviteForm.setContent('<center><img src=http://images.fotki.com/progress.gif> <span class=\"text2b black\">'+LangDict.translateToken('Lite.Albums.Invite.Loading')+'</span></center>');
		setTimeout('DialogInviteForm.show();', 20);	  
	},			 
	onSuccess : function(obj) {
		var response = obj.responseText.split("||");
		DialogInviteForm.setContent(response[0]);
		eval(response[1]);
	}
	});
}


function addemail(email) {
	document.emailform.to.focus();
	if (document.emailform.to.value == 0) {
		document.emailform.to.value = email;
	} else {
		var index = document.emailform.to.value.indexOf("," + email);
		if (index == -1){
			index = document.emailform.to.value.indexOf(", " + email);
		}
		if (index == -1) {
			document.emailform.to.value=document.emailform.to.value+', '+email;
		} else {
			var regexp = new RegExp("," + email);
			var regexp2 = new RegExp("," +email);
			var regexp3 = new RegExp(", "+email);
			document.emailform.to.value = document.emailform.to.value.replace(regexp3, "");
			document.emailform.to.value = document.emailform.to.value.replace(regexp, "");
			document.emailform.to.value = document.emailform.to.value.replace(regexp2, "");
		}
	}
}

function checkEmailRun() {
	Core.setText('email_error', "");
	Core.setText('message_error', "");
	var check1 = checkEmails('field_to');
	var check2 = checkEmails('email_from');
	if (check1) { // if error
		Core.setText('email_error', trans_email_format);
	} else if (check2){
		Core.setText('from_error', trans_email_format); 
	} else if (!(Core.getText('field_to'))) {
		Core.setText('email_error', trans_enter_email);
	} else if (!(Core.getText('user_name')) || trim(Core.getText('user_name')).length == 0) {
		Core.setText('from_error',trans_enter_name);
	} else if (!(Core.getText('email_from'))) {
		Core.setText('from_error', trans_enter_your_email);
	} else if (!(Core.getText('message_text'))) {
		Core.setText('message_error', trans_enter_text);
	} else {
		sendEmail();
	}
}

function checkEmails(field){
	var txt = Core.getText(field); //specify the id of textarea
	var e_regexp = new RegExp("^([A-Za-z0-9\-\_\.])+@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,4}$");
	var error = 0; // by default we have no error
	
	txt = txt.replace(/\n/g, "");
	txt = txt.replace(/\r/g, "");
	txt = txt.replace(/ /g, "");
   txt = trim(txt);
   if (txt.length == 0) {
      return 1;
   }
	var matches = txt.split(",");

	for (var i = 0; i < matches.length; i++) {
	if (matches[i]) {
		var email = matches[i];
			if (!email.match(e_regexp)) { // if didn`t match - error is 1
				error = 1; 
			}
		}
	}
	return error;
}

var mailservice = 'fotki';

function setServ(type) {
	mailservice = type;
}

function encryptForInvite(str, pwd) {
	if(pwd == null || pwd.length <= 0) {
		alert("Please enter a password with which to encrypt the message.");
		return null;
	}
	var prand = "";
	for(var i=0; i<pwd.length; i++) {
		prand += pwd.charCodeAt(i).toString();
	}
	var sPos = Math.floor(prand.length / 5);
	var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
	var incr = Math.ceil(pwd.length / 2);
	var modu = Math.pow(2, 31) - 1;
	if(mult < 2) {
		alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
		return null;
	}
	var salt = Math.round(Math.random() * 1000000000) % 100000000;
	prand += salt;
	while(prand.length > 10) {
		prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
	}
	prand = (mult * prand + incr) % modu;
	var enc_chr = "";
	var enc_str = "";
	for(var i=0; i<str.length; i++) {
	enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
	if(enc_chr < 16) {
		enc_str += "0" + enc_chr.toString(16);
	} else enc_str += enc_chr.toString(16);
		prand = (mult * prand + incr) % modu;
	}
	salt = salt.toString(16);
	while(salt.length < 8)salt = "0" + salt;
	enc_str += salt;
	return enc_str;
}

function getContact() {

	var login = Core.getText("login");
	var password = Core.getText("password");
 
   if (!login) {
      Core.setText('error',trans_enter_login);
      Core.showElement('error');
      return;
   }
   if (!password) {
      Core.setText('error',trans_enter_password);
      Core.showElement('error');
      return;
   }
	
	if (mailservice == 'fotki') {
	
		password = encryptForInvite(password, iv_key);
	
		advAJAX.post({
		"login" : login,
		"passwd"	 : password,
		"cmd"		 : "get_contact",
		"mailservice" : mailservice,
		"iv_ssid" : iv_ssid,
		timeout : 28900,
	onTimeout : function() {
		Core.setText('loading', ''); 
		Core.setText('error', 'Connection timed out. Please try again.');
		Core.showElement('error');
	},
	onLoading : function (obj) {
		Core.hideElement('error');
		Core.setText('error', '');
		Core.setText('loading', '<img src=http://images.fotki.com/progress.gif> ');
	},
	onSuccess : function(obj) {
		var n = obj.responseText.indexOf('<!DOCTYPE'); 
		if (n == 0)	 {
			Core.setText('password', '');
			Core.setText('loading', '');
			Core.setText('error', trans_incor_uname_passwd);
			Core.showElement('error');
		} else {		 
			Core.hideElement('login_form');
			Core.setText('loading', '');
			Core.setText('login', '');
			Core.setText('password', '');
			Core.setText('add_book_' + mailservice, obj.responseText);
		}
	}
	});
	
	} else {
	
	password = password;
	
		advAJAX.post({
		"login" : login,
		"passwd"	 : password,
		"cmd"		 : "get_contact",
		"mailservice" : mailservice,
		timeout : 28900,
	onTimeout : function() {
		Core.setText('loading', ''); 
		Core.setText('error', 'Connection timed out. Please try again.');
		Core.showElement('error');
	},
	onLoading : function (obj) {
		Core.hideElement('error');
		Core.setText('error', '');
		Core.setText('loading', '<img src=http://images.fotki.com/progress.gif> ');
	},
	onSuccess : function(obj) {
		var n = obj.responseText.indexOf('Error'); 
		if (n == 0)	 {
			Core.setText('password', '');
			Core.setText('loading', '');
			Core.setText('error', obj.responseText.substr(n + 7));
			Core.showElement('error');
		} else {		 
			Core.hideElement('login_form');
			Core.setText('loading', '');
			Core.setText('login', '');
			Core.setText('password', '');
			Core.setText('add_book_' + mailservice, obj.responseText);
		}
	}
	});
	
	}
}

function sendEmail() {
	var display_name = Core.getText('user_name');
	var subject_text = display_name + Core.getText("subject_text");
	var checkbox = '';
	if (Core.getElementU('checkbox')) {
		checkbox =	'' + Core.getElementU("checkbox").checked;		
	}

	var pid =	 '';
	var is_ecard = '';

	if (Core.getElementU('is_ecard')){
		is_ecard = Core.getText('is_ecard');
	}

	if (Core.getElementU('pid')) {
		pid =	 Core.getText("pid");
		progress_text = "E-card sending...";
		limit_text = "Dayly e-cards limit reached";
		complite_text = "E-card sent";
	} else {
		progress_text = "Sending invitation...";
		limit_text = "Daily invitation limit reached";
		complite_text = LangDict.translateToken('Lite.Albums.Invite.InvitationSent');
	}

	advAJAX.post({
		"cmd"		 : "invite_sendemail",
		"to"		 : Core.getText("field_to"),
		"subject" : subject_text,
		"text"	 : Core.getText("message_text"),
		"checkbox" : checkbox,
		"email_from" : Core.getText("email_from"),
		"user_name"	 : display_name,
		"pid"	  : pid,
		"is_ecard" : is_ecard,
		onLoading : function (obj) {
		  DialogInviteForm.hide();
        DialogInviteSending = new ModalDialog('<center><img src=http://images.fotki.com/progress.gif> <span class=\"text2b black\">'+progress_text+'</span></center>');

//		  Core.setText('album_invite_sending', '<center><img src=http://images.fotki.com/progress.gif> <span class=\"text2b black\">'+progress_text+'</span></center>');
//		  DialogInviteSending = new ModalDialog('album_invite_sending');
		  DialogInviteSending.show();
	 },
		onSuccess : function(obj) {
			var n = obj.responseText.indexOf('ERROR'); 
		setTimeout('DialogInviteSending.hide();', 3000);
		  if (n == 0)	{
           DialogInviteComplete = new ModalDialog('<center><span class=\"text2b black\"><img src=http://images.fotki.com/cart/warning.gif>'+limit_text+'</span></center>');

		 // Core.setText('album_invite_complete', '<center><span class=\"text2b black\"><img src=http://images.fotki.com/cart/warning.gif>'+limit_text+'</span></center>');
		 // DialogInviteComplete = new ModalDialog('album_invite_complete');
		  setTimeout('DialogInviteComplete.show();', 3000);
		  setTimeout('DialogInviteComplete.hide();', 5000);
		} else {		 
			//Core.setText('album_invite_complete', '<center><img src=http://images.fotki.com/cart/ok.gif> <span class=\"text2b black\">'+complite_text+'</span></center>');
			//DialogInviteComplete = new ModalDialog('album_invite_complete');
         DialogInviteComplete = new ModalDialog(  '<center><img src=http://images.fotki.com/cart/ok.gif> <span class=\"text2b black\">'+complite_text+'</span></center>');

			setTimeout('DialogInviteComplete.show();', 3000);
			setTimeout('DialogInviteComplete.hide();', 5000);
		}
	 }
	});
}

function setBg(element, bg) {
	element.style.background=bg;
}

function trim(str) {
    str = str.replace(/^\s*/, '').replace(/\s*$/, '');
   return str;
}

function changeMailType(type) {
	var mails = ['hotmail', 'yahoo', 'fotki', 'gmail'];
	for (var i in mails) {
		if (mails[i] == type) {
			setServ(type);
			Core.setClassName(mails[i] + '_td', 'arrow_' + mails[i]);
			if ((mails[i] == "fotki" && member == false) || mails[i] != "fotki") {
				Core.showElement('login_form');
			} else {
				Core.hideElement('login_form')
			}
			Core.showElement("add_book_" + mails[i]);
         if (Core.getText("add_book_" + mails[i])) {
            if (trim(Core.getText("add_book_" + mails[i]))) {
               Core.hideElement('login_form');
            }
         }
		} else {
			Core.setClassName(mails[i] + '_td', '');
			Core.hideElement('error', '');
			Core.hideElement('add_book_' + mails[i]);
		}
	}
}

