var folderStat;

// Change to enable jsoncallback (JSONP) - Make sure the Webadmin > Services > API > JSONP = On to enable
var jsoncallback = 0;

$.fn.setjsoncallback = function(val) {

	jsoncallback = val;

}

$.fn.jsoncallback = function() {

	if(jsoncallback == 1) {
		return '?jsoncallback=?'
	
	} else {
		// Return the plain JSON data only, do not request JSONP data from the server ( cross domain )
		return '';	
	}

}

$.fn.loadContacts = function(url, type) {
		
	// First, load the read/total/unread
	var contactUrl = url + "index.php/api/contact/list/GroupID/" + type + $(this).jsoncallback();
	var params = { format: 'json' };

	$("DIV#ContactList").html("");
	
	$.getJSON(contactUrl, params, function(json) { 
        if ( json ) {
			$.each( json, function(i, n) { 
			var item = json[i];
			
			var row = $("DIV.ContactRowTemplate").clone();
			
			row.removeClass('ContactRowTemplate');
			row.show();
			
			// Add the photo
			if(item.UserPhoto)
				$('IMG#UserPhoto', row).attr('src','data:image/png;base64,'+ item.UserPhoto);
			else
				$('IMG#UserPhoto', row).attr('src','../../images/contact-photo-blue.png');
			
			$('DIV#UserFirstName', row).html(item.UserFirstName);
			$('DIV#UserLastName', row).html(item.UserLastName);
			$('DIV#UserEmail', row).html(item.UserEmail);
			
			$("DIV#ContactList").append(row);
			});

		}
	});

}

$.fn.loadMailTabs = function(url, folder) {
	
	//Default Action
	$(".tab_content").hide(); //Hide all content
	$("ul.tabs li:nth-child(2)").addClass("active").show(); //Activate first tab
	$(".tab_content:nth-child(2)").show(); //Show first tab content

	//On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
	});
		
	// First, load the read/total/unread
	var mailUrl = url + "index.php/api/mail/status/" + $(this).jsoncallback();
	var params = { format: 'json' };

    if(folder != 'Inbox') {
    
		$.getJSON(mailUrl, params, function(json) { 

	        if ( json ) {

            folderStat.recent = json.recent;
            folderStat.unseen = json.unseen;
            folderStat.exists = json.exists;
			
			}
		});
        
    } else {
    
    }
    
    $("SPAN.recent").text(folderStat.recent);
    $("SPAN.unseen").text(folderStat.unseen);
    $("SPAN.total").text(folderStat.exists);
    
    $("DIV.container").fadeIn('fast');
	
	// Next, fetch all the new email messages
	var mailUrl = url + "index.php/api/mail/list/limit/3/" + $(this).jsoncallback();
	var params = { format: 'json' };

		$.getJSON(mailUrl, params, function(json) { 

	        if ( json ) {
		
				$.each( json, function(i, n) { 
				//alert(i);
				var item = json[i];
				
				if(item.basicHeaders) {
					var str = item.basicHeaders.date;
					html = "<li class='msgrow'><a href='" + url + "'>" + item.basicHeaders.from + "</a> <span class='date'>" + jQuery.timeago( str ) + "</span> <div class='preview'>" + json[i+1].preview + "</div></li>";
					$("UL.msgList").append(html);
				}
		
				
				});

			}
		});	
		
	// Last, get our calendar events!
	var calendarUrl = url + "index.php/api/calendar/list/" + $(this).jsoncallback();
	var params = { format: 'json' };

		$.getJSON(calendarUrl, params, function(json) { 
			var events = 0;

	        if ( json ) {
		
				$.each( json, function(i, n) { 

				var item = json[i];
				
				if(item.DateStartCal) {
					var str = item.DateStartCal + " " + item.DateStartTime;
					html = "<li class='calendarrow'><a href='" + url + "'>" + item.Title + "</a> <span class='date'>" +  str + "</span></li>";
					$("UL.calendarList").append(html);
				}
		
				events++;
				
				});

			}

			$("SPAN.eventsTotal").text(events);


		});	

}

$.fn.loadStatus = function(url, folder) {

    var mailUrl = url + "index.php/api/mail/status/" + $(this).jsoncallback();
    var params = { format: 'json' };

    // If the folder has already been loaded ( e.g first connect ) return the original string
    // Otherwise the new messages will be unavilable in the next hit
    if ( folderStat && folder == 'Inbox' ) { 

        var recent = folderStat.recent;
        if(!recent)
            recent = 0;

        var unseen = folderStat.unseen;
        if(!unseen)
            unseen = 0;
			
		$("#recent").text(recent + " new").attr('href', url);
		$("#unseen").text(unseen + " unread messages").attr('href', url);
		
		$("div.status").fadeIn('fast');			

    } else {
    
        $.getJSON(mailUrl, params, function(json) { 

			var recent = json.recent;
			if(!recent)
				recent = 0;

			var unseen = json.unseen;
			if(!unseen)
				unseen = 0;

			$("#recent").text(recent + " new").attr('href', url);
			$("#unseen").text(unseen + " unread messages").attr('href', url);
			
			$("div.status").fadeIn('fast');
			
		});

    }

};

$.fn.checkLogin = function(args) {
	
	// Check if we can login ( does our cookie work? )
	var authUrl = args.url + "index.php/api/mail/auth/" + $(this).jsoncallback();
	var params = { format: 'json' };
	
	$.getJSON(authUrl, params, function(json) { 
        if ( json ) { 

			if(json.message == 'OK') {
                folderStat = json.folderStat;
				args.success(args.url);
			} else {
				args.error();
			}
		}
		
	});
	
};


