/**
 * Created with Emacs.
 * User: atmail
 * Date: 22/05/12
 * Time: 1:53 PM
 */

$contact = {
	_currentGroup : null,
	_currentContact : null,
	_groups       : null,
	_contacts     : {}
};

$contact.clearCache = function() {
	this._contacts = {};
	this._groups = null;
	this._currentContact = null;
	this._currentGroup = null;
};

$contact.getCurrentGroup = function() {
	return this._currentGroup;
};

$contact.setCurrentGroup = function(val) {
	this._currentGroup = val;
};

$contact.idToKey = function(groupId) {
	if(!groupId) groupId = 0;
	return "GID" + groupId;
}

$contact.empty = function() {
	this._contacts = {};
}

$contact.clearGroup = function(groupId) {
	var key = this.idToKey(groupId);
	$contact._contacts[key] = null;
}

/**
 * get cached contact. it will
 * @param groupId
 * @param callback
 * @return {*}
 */
$contact.getContacts = function(groupId, callback) {

	var key = this.idToKey(groupId);

	if(callback) {
		if($contact._contacts[key]) {
			callback($contact._contacts[key]);
		}
		else {
			$mobile.listContacts(groupId, function(json){
				if(json instanceof Array) {
					$contact._contacts[key]	= json;
					callback(json);
				}
				else {
					callback([]);
				}
			});
		}
	}
};

$contact.deleteContact = function(contactId, groupId, callback) {

	if(!(contactId instanceof Array)) {
		contactId = [contactId];
	}

	var postData = {
		"id[]"  : contactId,
		GroupID : groupId
	};

	var url = $group.isDroppable(groupId)? "api/contact/deletefromgroup" : "api/contact/delete";
	$mobile.postJSON(url, postData, callback);

	this.empty();
};

$contact.move = function(ids, groupId, callback) {

	if(!(ids instanceof Array)) {
		ids = [ids];
	}

	var postData = {
		GroupID : groupId,
		"id[]"  : ids
	}

	$mobile.postJSON("api/contact/addtogroup", postData, callback);

	this.empty();
}

$contact.getGroups = function(callback) {

	if(callback) {
		if($contact._groups instanceof Array && $contact._groups.length) {
			callback($contact._groups);
		}
		else {
			$mobile.loadGroups(function(json){
				if(json instanceof Array) {
					$contact._groups = json;
					callback(json);
				}
				else {
					callback([]);
				}
			});
		}
	}
};

$contact.createGroup = function(name, callback) {
	$mobile.createGroup(name, function(json) {
		if(json && json['result'] == 'success') {
			$contact._groups.push(json.data);

			callback && callback(json);
		}
	})
}

$contact.deleteGroup = function(id, callback) {
	$mobile.deleteGroup(id, function(json) {

		if($contact._groups instanceof Array && $contact._groups.length) {

			var index = -1;
			for(var i=0; i<$contact._groups.length; ++i) {
				var data = $contact._groups[i];

				if(data.id === id) {
					index = i;
					break;
				}
			}

			if(index >= 0 ) {
				$contact._groups.splice(index,1);
			}
		}

		callback && callback(json);
	})
}

$contact.setContacts = function(groupId, contacts) {
	var key = this.idToKey(groupId);
	this._contacts[key] = contacts;
};

$contact.getCurrentContact = function() {
	return this._currentContact;
}

$contact.setCurrentContact = function(val) {
	this._currentContact = val;
}

$contact.getDisplayName = function(firstName, lastName) {
	if(firstName && lastName) return firstName + ' ' + lastName;
	else {
		return firstName || lastName;
	}
};

$contact.searchEmail = function(email) {
	var contactsAll = this._contacts[0];

	if(!contactsAll) return null;

	for(var i=0; i<contactsAll.length; ++i) {
		var contact = contactsAll[i];

		for(var key in contact) {
			if(contact[key] === email) return contact;
		}
	}

	return null;

}

$contact.getCompanyLogo = function(email) {

	if(!email || email.indexOf('@') == -1) return null;

	var domain = email.split('@')[1].trim().toLowerCase();

	if(!domain) return null;

	var map = {
		'atmail'                  : 'atmail-logo.png',
		'yahoo.com'               : 'yahoo-logo.png',
		'hotmail.com'             : 'hotmail-logo.png',
		'facebook'                : 'fb-logo.png',
		'ebay.com'                : 'ebay-logo.png',
		'foursquare.com'          : 'foursquare-logo.png',
		'gmail.com'               : 'gmail-logo.png',
		'google.com'              : 'google-logo.png',
		'twitter.com'             : 'twitter-logo.png',
		'postmaster.twitter.com'  : 'twitter-logo.png'
	};

	var logo = null;

	for(var k in map) {
		if( domain.indexOf(k) >= 0 ) {
			logo = map[k];
			break;
		}
	}

	if(!logo) return null;

	return getSiteBaseUrl() + "images/mobile/logo/" + logo;
}

$contact.getFieldDisplayName = function(fieldName) {
	var fieldNameMap = {
		UserEmail       : "Email",
		UserEmail2      : "Email2",
		UserEmail3      : "Email3",
		UserEmail4      : "Email4",
		UserEmail5      : "Email5",
		UserFirstName   : "First Name",
		UserMiddleName  : "Middle Name",
		UserLastName    : "Last Name",
		UserTitle       : "Title",
		UserGender      : "Gender",
		UserDOB         : "D.O.B",
		UserHomeAddress : "Address",
		UserHomeCity    : "City",
		UserHomeState   : "State",
		UserHomeZip     : "Zip",
		UserHomeCountry : "Country",
		UserHomePhone   : "Home Phone",
		UserHomeMobile  : "Home Mobile",
		UserHomeFax     : "Home Fax",
		UserURL         : "URL",
		UserWorkCompany : "Company",
		UserWorkTitle   : "Work Title",
		UserWorkDept    : "Work Department",
		UserWorkOffice  : "Work Office",
		UserWorkAddress : "Work Address",
		UserWorkCity    : "WorkCity",
		UserWorkState   : "WorkState",
		UserWorkZip     : "WorkZip",
		UserWorkCountry : "WorkCountry",
		UserWorkPhone   : "Work Phone",
		UserWorkMobile  : "Work Mobile",
		UserWorkFax     : "Work Fax",
		UserType        : "Type",
		UserPhoto       : "Photo",
		Favourite       : "Favourite",
		UsageCount      : "UsageCount"
	};

	return !fieldName ? 'Unknown' : ( fieldNameMap[fieldName] ? fieldNameMap[fieldName] : fieldName );

};


/**
 * Object functions for managing group
 * @type {Object}
 */

var $group = {};

$group.isDroppable = function(gid) {
	return gid>0 || gid==-2 || gid==-4;
};
