var contacts;

var JSON = JSON || {};
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
	var t = typeof (obj);
	if (t != "object" || obj === null) {
		// simple data type
		if (t == "string") obj = '"'+obj+'"';
		return String(obj);

	}
	else {
		// recurse array or object
		var n, v, json = [], arr = (obj && obj.constructor == Array);
		for (n in obj) {
			v = obj[n]; t = typeof(v);

			if (t == "string") v = '"'+v+'"';
			else if (t == "object" && v !== null) v = JSON.stringify(v);

			json.push((arr ? "" : '"' + n + '":') + String(v));
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
};

// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
	if (str === "") str = '""';
	eval("var p=" + str + ";");
	return p;
};

String.fromCharRefs = function(str) {
	try{
        var element = document.createElement("div");
        element.innerHTML = str;		
		var teststr = element.firstChild.data;
		var bstr = '';
		for(i=0; i<teststr.length; i++)
		{
			if(teststr.charCodeAt(i)==8211)
			{
				bstr += '&ndash;';
			}
			else
			{
				bstr += teststr.charAt(i);
			}
		}
        return bstr;
	}
	catch(err){
		//alert(err.toSource());
	}
};

function convertToUnicode(tstr){
	var bstr = '';
	for(i=0; i<tstr.length; i++)
	{
		if(tstr.charCodeAt(i)>127)
		{
			bstr += '&#' + tstr.charCodeAt(i) + ';';
		}
		else
		{
			bstr += tstr.charAt(i);
		}
	}
	return bstr;
}

function parseXMLtoJSON(xmlurl){
	$.ajax({
		url: xmlurl,
		type: "GET",
		dataType: ($.browser.msie) ? "text" : "xml",
		cache: true,
		error: function(jqXHR, textStatus, errorThrown){
			//alert('errorThrown');
		},	
		success: function(data){		
			if (typeof data == "string") {
				xml = new ActiveXObject("Microsoft.XMLDOM");
				xml.async = false;
				xml.loadXML(data);
			} 
			else {
				xml = data;
			}
			contacts = $.xml2json(xml);//CONVERT XML to JSON			
		},
		complete: function(jqXHR, textStatus){
			if(textStatus == "success"){
				setTimeout(function(){
					var contactid = "";
					var $parentrow = null;
					$('.contactcard').each(function(){
						contactid = $(this).attr('class').split(' ').slice(-1);
						$parentrow = $(this).parents('tr.entry');
						if($(this).hasClass('individual')){
							getContacts(contactid,$parentrow,"individual",$(this).text());
						}
						else if($(this).hasClass('group')){
							getContacts(contactid,$parentrow,"group",$(this).text());
						}
					});
				},1000);			
			}
		}
	});
}

function getContacts(searchkey, parentrow, contacttype, contactname){	
	if(contacts.contact.length > 0){
		var filteredContacts = $.grep(contacts.contact, function(el) {
			return ((JSON.stringify(el.tags)).toString().toLowerCase().indexOf($.trim(searchkey).toLowerCase())>-1)		
			});
		var matches = 0;
		if(filteredContacts.length > 0){
			var content = [""];
			$.each(filteredContacts, function(){
				if(contacttype=="individual"){//FOR INDIVIDUAL CONTACTS
					content.push('<div class="contacthead">');
					content.push('<div class="contactname">'+convertToUnicode(this.name)+'</div>');
					
					if($.trim(this.role).length > 0){
						content.push('<div class="contactrole">'+this.role+'</div>');
					}
					else{
						content.push('<div class="contactrole">&nbsp;</div>');
					}
					
					if($.trim(this.country).length > 0){
						content.push('<div class="contactspeciality">'+this.country+'</div>');
					}
					else{
						content.push('<div class="contactspeciality">&nbsp;</div>');
					}
					
					content.push('<div class="contactpreviewbtn"><a href="#" class="previewclose linkdown floatright" title="Click to preview contact details.">preview</a></div>');
					content.push('</div>');
					
					content.push('<div class="contactdetails">');
					content.push('<div class="close"><a href="#" class="previewclose linkup" title="Click to hide contact details."><strong>close</strong></a></div>');
					
					if ($.trim(this.image).length > 0) {
						content.push('<div class="image"><img src="'+this.image+'" height="150" width="180" border="0" alt="'+this.name+'"/></div>');
					}
					
					content.push('<div class="content">');
					content.push('<div class="previewdetails">');
					content.push('<h2 class="secondaryintrotextsmall">'+convertToUnicode(this.name)+'</h2>');
					if(this.role.length>0){
						content.push('<p>'+this.role+'</p>');
					}						
					content.push('<div class="detailsbox">');
					
					if(this.details.email){
						if(this.name){
						content.push('<span class="secondarybutton roundcorner floatleft" ><a href="#" title="Send an e-mail" class="roundcorner" onclick="showModalDialog(\'/gbm/features/feedback/gbm-contacts-feedback.html?contact_name='+escape(String.fromCharRefs(this.name))+'&amp;contact_card_id='+this.tags.contactid+'\');return false;">Contact</a></span>');
						}
						else{
						content.push('<span class="secondarybutton roundcorner floatleft" ><a href="#" title="Send an e-mail" class="roundcorner" onclick="showModalDialog(\'/gbm/features/feedback/gbm-contacts-feedback.html?contact_card_id='+this.tags.contactid+'\');return false;">Contact</a></span>');
						}
					}
					
					content.push('<p class="floatleft">');
						if (this.details.tel != '') {
							content.push('Phone:&nbsp;&nbsp;'+this.details.tel+'<br/>');
						}
						if (this.details.fax != '') {
							content.push('Fax:&nbsp;&nbsp;'+this.details.fax+'<br/>');
						}
						if (this.details.address != '') {
							content.push('Address:&nbsp;&nbsp;'+this.details.address+'<br/>');
						}
					content.push('</p>');			
					content.push('</div></div></div></div>');
					matches++;
				}
				else if(contacttype=="group"){//FOR GROUP CONTACTS			
					content.push('<div class="groupcontacthead">');
					content.push('<div class="groupcontactname">'+convertToUnicode(this.name)+'</div>');
					content.push('<div class="groupcontactspeciality">&nbsp;</div>');
					content.push('<div class="contactpreviewbtn"><a href="#" class="previewclose linkdown floatright" title="Click to preview contact details.">preview</a></div>');
					content.push('</div>');
					
					content.push('<div class="contactdetails">');
					content.push('<div class="close"><a href="#" class="previewclose linkup" title="Click to hide contact details."><strong>close</strong></a></div>');
					
					content.push('<div class="content">');
					content.push('<div class="previewdetails">');
					content.push('<h2 class="secondaryintrotextsmall">'+convertToUnicode(this.name)+'</h2>');
					content.push('<p>'+this.country+'</p>');
					
					content.push('<div class="detailsbox">');
					
					if(this.details.email){
						if(this.name){
						content.push('<span class="secondarybutton roundcorner floatleft" ><a href="#" title="Send an e-mail" class="roundcorner" onclick="showModalDialog(\'/gbm/features/feedback/gbm-contacts-feedback.html?contact_name='+escape(String.fromCharRefs(this.name))+'&amp;contact_card_id='+this.tags.contactid+'\');return false;">Contact</a></span>');
						}
						else{
						content.push('<span class="secondarybutton roundcorner floatleft" ><a href="#" title="Send an e-mail" class="roundcorner" onclick="showModalDialog(\'/gbm/features/feedback/gbm-contacts-feedback.html?contact_card_id='+this.tags.contactid+'\');return false;">Contact</a></span>');
						}
					}
					
					content.push('<p class="floatleft">');
						if(this.details.tel != ''){
							content.push('Phone:&nbsp;&nbsp;'+this.details.tel+'<br/>');
						}
						if(this.details.fax != ''){
							content.push('Fax:&nbsp;&nbsp;'+this.details.fax+'<br/>');
						}
						if(this.details.address != ''){
							content.push('Address:&nbsp;&nbsp;'+this.details.address+'<br/>');
						}
					content.push('</p>');
					content.push('</div>');
					content.push('<p>'+this.info+'</p>')
					content.push('</div></div></div>');
					matches++;
				}		
				parentrow.find('td').html(content.join(""));
			});
			if(matches == 0){
				parentrow.find('td').html('<div class="contacthead" style="display: block;"><div class="contactname">'+contactname+'</div></div>');
			}
		}
	}
}

function initializePIEforTable(elem){
	if ($.browser.msie && $.browser.version.substr(0,1)<9) {
		if(window.PIE) {
			elem.parents('td').find('.contactdetails .roundcorner').each(function() {
				PIE.attach(this);
			});
		}			
	}
}

$(document).ready(function(){
	if($('.contactcard').length > 0){
		parseXMLtoJSON("/gbm/features/common/tools/contact_finder_data.xml");
	}
});

$(window).load(function(){
	if ($.browser.msie && $.browser.version.substr(0,1)<9) {
		if(window.PIE) {
			if($('table.contactcontent').length > 0){
				setTimeout(function(){
					$('table.contactcontent .contactdetails .roundcorner').each(function() {
						PIE.attach(this);
					});
				},3000);
			}
		}			
	}
});
