/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

//method called for prepping the view message body iframe
function prepMessageIframe( obj, base_url, content_url)
{
	var hidden_message_body = $(obj).prev(); 						// hidden message body, ready to render
	var message_iframe = $(obj);									// iframe target
	var message_contents = $('body', message_iframe.contents() );	// jquery selector of iframe contents
	
	// Style for iframe
	var style = "body { font: 12px/1.3 \"Helvetica Neue\",Helvetica,Arial,sans-serif; color: #333333; line-height: 1.6; }\n" +
				"a { color: #aaaaaa; }\n" +
				".messageBody blockquote { border-left: 1px solid #CCCCCC; margin-left: 10px; padding-left: 4px; }\n" +
				".badimagesdisabled { background: url('" + base_url + "images/blocked_image.png') no-repeat scroll center center transparent; cursor:pointer; min-height: 40px; min-width: 40px; border: 1px #E3E3E3 solid; }\n" +
				"* .badimagesdisabled { height: expression( this.scrollHeight < 41 ? '40px' : 'auto' ); width: expression( this.scrollWidth < 41 ? '40px' : 'auto' ); }\n" +
				".highlight { background-color: #B5D5FF; }" +
				"#bodyWrapper { .overflow-x: scroll }";
	
	// ***************************** CACHING ********************************* //
	// strip the context, as we dont really care where it gets rendered too at this stage
	// BUT we DO care if this is an unique rendering
	// we must preserve 'attachmentId'

	uniqueId = '';
	if(content_url.indexOf('uniqueId') != -1)
	{
		uniqueId = content_url.substring(content_url.indexOf('uniqueId'));
	}


	if(content_url.indexOf('messagePanelContextName') != -1)
	{
		content_url = content_url.substring(0, content_url.indexOf('messagePanelContextName'));
		if(content_url.indexOf('uniqueId') == -1)
		{
			content_url = content_url + uniqueId;
		}
	}

	var message_contents_html = '';
	
	// check if we are cached
	if($.jCacher.get(content_url))
	{
		// yup, reload the contents
		message_contents_html = $.jCacher.get(content_url).value;
	}
	else
	{
		// construct message iframe html
		message_contents_html = "<style>" + style + "</style>" + "<div id=\"bodyWrapper\">" + (hidden_message_body.text()) + "</div>";

		// nope perhapes first render?
		// remove in case stale then cache the result
		$.jCacher.remove(content_url);
		$.jCacher.add(content_url, message_contents_html, 3600);
	}

	message_iframe.attr('content_url', content_url);
	
	// ***************************** LOAD HTML ********************************* //
	// load and prepare/render iframe
	message_contents.html(message_contents_html);
	prepMessageBody( message_iframe );
	prepMessageIframeHeight( message_iframe );	

    var imagesSelector = message_iframe.contents().find("img");
    var totalImagesToLoad = imagesSelector.length;

    checkImagesLoaded(message_iframe, totalImagesToLoad);

    imagesSelector.each(function(index)
    {
        $(this).each( function()
        {
            $(this).error( function() { countImagesLoaded($(this), message_iframe); $(this).unbind('error'); } );
            $(this).load( function() { countImagesLoaded($(this), message_iframe); $(this).unbind('load'); } );
        });
    });

    // ***************************** LOAD IMAGES ********************************* //
	// count the amount of images that are not being rendered
	// so we can decide if the show images button is applicable to this pane
	var images = message_contents.find('img[badsrc]');
	var backgrounds = message_contents.find('*[badbackground]');

	var counter = images.length + backgrounds.length;
	if(counter == 0)
	{
		// if all the images are already shown....
		// hide the show images button
        message_iframe.parent().parent().find('#nodeImagesAnchor').parent().hide();
        message_iframe.parent().parent().find('#displayimage').hide();
	}
	else
	{
		var message_iframe_parent = message_iframe.parent().parent();
		if(message_iframe_parent.is('ul'))
		{
            message_iframe_parent = message_iframe.parent().parent().parent().parent().parent();
		}
        //message_iframe_parent.find('#nodeImagesAnchor').parent().show();
        message_iframe_parent.find('#displayimage').show();
	}

    var message_html = $('html', message_iframe.contents());
    if($.browser.msie && $.browser.version == 7)
    {
        // ie7 must have scroll bar hidden specifically.
        message_html.css({'overflow-x' : 'hidden'});
    }
}

// method called for prepping the view message body iframe height
function prepMessageIframeHeight( iframeobj )
{
    var currentHeight = 0;
    var contents = 0;
    if(iframeobj == undefined || iframeobj.get(0) == undefined || (iframeobj.get(0).contentWindow == undefined && iframeobj.get(0).contentDocument == undefined))
    {
        return;
    }
    if(iframeobj.contents() != undefined)
    {
        currentHeight = $('#bodyWrapper', iframeobj.contents() ).innerHeight();
    }
    else
    {
        return;
    }

	if(currentHeight == undefined || currentHeight == 0)
	{
		currentHeight = $('body', iframeobj.contents() ).innerHeight();

		if(currentHeight == undefined || currentHeight == 0)
		{
			// we failed to retrieve the iframe height
			// most probably this is due to hidden iframe
			// so abort
			return
		}
	}
	iframeobj.height( currentHeight + 50 );
}

function prepMessageBody( $srcObj )
{

	//first clean it up
	convertQuotedToShowQuoted( $srcObj );
	
	//cleanScripts( $srcObj );
	
	//make anchor tags open in new window
	$("a", $srcObj.contents()).attr('target', '_blank');

}

function countImagesLoaded(_this, sourceNode)
{
    var totalImagesToLoad = sourceNode.data('totalImagesToLoad');
    totalImagesToLoad--;
    sourceNode.data('totalImagesToLoad', totalImagesToLoad);
}

function checkImagesLoaded(sourceNode, totalImagesToLoad)
{
    var checkTimeout = 250; //ms
    var timerId = sourceNode.data('timerId');
    if(timerId == undefined && totalImagesToLoad != 0)
    {
        // first time init
        sourceNode.data('totalImagesToLoad', totalImagesToLoad);
        sourceNode.data('timerId', setInterval(function() { checkImagesLoaded(sourceNode, totalImagesToLoad) }, checkTimeout));
        sourceNode.data('totalRunningTime', 0);
    }
    else
    {
        sourceNode.data('totalRunningTime', sourceNode.data('totalRunningTime') + checkTimeout);
        // the last time and every 'checkTimeout' ms (setInterval) or after 180000ms (3 mins)
        if(sourceNode.data('totalRunningTime') > 180000 || sourceNode.data('totalImagesToLoad') == 0 || sourceNode.is(":hidden"))
        {
            clearInterval(sourceNode.data('timerId'));
            sourceNode.data('totalImagesToLoad', null);
            sourceNode.data('timerId', null);
        }

        prepMessageIframeHeight( sourceNode );
    }
}

function loadImages(sourceNode)
{
	var iframes = $(sourceNode).find('.messageIframe');
	if ( iframes.length > 0 )
	{
		iframes.each( function()
		{
			message_iframe = $(this);
			content_url = $(this).attr('content_url');
			
			body = $(this).contents();
            var disabledImagesSelector = body.find(".badimagesdisabled");
            var disabledBackgroundsSelector = body.find('[badbackground]');
            var totalImagesToLoad = disabledImagesSelector.length + disabledBackgroundsSelector.length;
            var resetCache = (totalImagesToLoad != 0);

            checkImagesLoaded(message_iframe, totalImagesToLoad);

            disabledImagesSelector.each(function(index)
			{
                $(this).each( function()
				{
					badsrc = $(this).attr("badsrc");
					badclass = $(this).attr("badclass");
					badtitle = $(this).attr("badtitle");
					$(this).removeAttr('badsrc');
					$(this).removeAttr('badclass');
					$(this).removeAttr('badtitle');

					if(badsrc == undefined || badsrc == '')
					{
						$(this).removeAttr('src');
					}
					else
					{
						$(this).attr("src", badsrc);
					}

					if(badclass == undefined || badclass == '')
					{
						$(this).removeAttr("class");
					}
					else
					{
						$(this).removeClass("badimagesdisabled");
						$(this).addClass(badclass);
					}

					if(badtitle == undefined || badtitle == '')
					{
						$(this).removeAttr("title");
					}
					else
					{
						$(this).attr("title", badtitle);
					}

					$(this).error( function() { countImagesLoaded($(this), message_iframe); $(this).unbind('error');} );
					$(this).load( function() { countImagesLoaded($(this), message_iframe); $(this).unbind('load'); } );
				});
			});
            disabledBackgroundsSelector.each(function(index)
			{
				badbackground = $(this).attr("badbackground");
				$(this).attr("background", badbackground); 
				$(this).removeAttr("badbackground");
				$(this).error( function() { countImagesLoaded($(this), message_iframe); $(this).unbind('error');} );
				$(this).load( function() { countImagesLoaded($(this), message_iframe); $(this).unbind('load');} );
			});

		    if(resetCache)
		    {
		    	html = message_iframe.contents().find('body').html();
				$.jCacher.remove(content_url);
			    $.jCacher.add(content_url, html, 3600);
		    }
			
			// adjust the iframe height as we have removed the 'bad' images (around 32px each)
			// so there will be a large gap at the bottom of the iframe.
			// during the checking of loaded images, we will update the height every 3-5 images
			// and a final after all images loaded.
			prepMessageIframeHeight( message_iframe );
		});
    }
}


function setTextBoxList( origionalFormObject, newArray, autocompleteList, autocompleteCacheSize, autocompleteFetchThreshold, autocompleteFetchSize, autocompleteMinFetchLength, autocompleteUrl)
{
	if(autocompleteCacheSize == undefined) autocompleteCacheSize = 100;
	if(autocompleteFetchThreshold == undefined) autocompleteFetchThreshold = 50;
	if(autocompleteFetchSize == undefined) autocompleteFetchSize = 25;
	if(autocompleteMinFetchLength == undefined) autocompleteMinFetchLength = 2;
	if(autocompleteUrl == undefined) autocompleteUrl = 'contacts/autocomplete/limit/';
	//return
	origionalFormObject.siblings('.textboxlist').remove()
	$(origionalFormObject).attr('value', '')
	var newTextBoxList = new TextboxList(origionalFormObject, {unique: true, bitsOptions:{editable: {addOnBlur:true}}, plugins: {autocomplete: {placeholder:false, cacheSize: autocompleteCacheSize}}});

	// Don't repopulated with null values
	if(autocompleteList != undefined)
	{
	
		newTextBoxList.plugins['autocomplete'].setValues(autocompleteList);
	
	}
	
	// above static lookup, enable dynamic lookup
	if(autocompleteList.length >= autocompleteFetchThreshold)
	{
		newTextBoxList.plugins['autocomplete'].setOptions( 
			{
				placeholder: false,
				cacheSize: autocompleteCacheSize,
				minRemoteLength: autocompleteMinFetchLength,
				queryRemote: true,
				remote: {url: (autocompleteUrl + 'contacts/autocomplete/limit/' + autocompleteFetchSize)}
			});
	}

	for(var index in newArray) {
		
		//already html entities
		//newArray[index] = $('<div/>').text( newArray[index] ).html()
		//TextboxList.add = function(plain, id, html, afterEl)
		if( newArray[index].length > 0 )
		{
			newArray[index] = $.trim(html_entity_decode(newArray[index]));

			// remove blank descriptions
			if(	newArray[index].indexOf('"" ') == 0 ||
				newArray[index].indexOf("'' ") == 0)
			{
				newArray[index] = newArray[index].substring(3);
			}
	
			// remove <> from just emails
			if(newArray[index][0] == '<' && newArray[index][newArray[index].length - 1] == '>')
			{
				newArray[index] = newArray[index].substring(1, newArray[index].length - 1);
			}

			newTextBoxList.add(newArray[index]); //, newArray[index], newArray[index]);
		}
	}
	
	return newTextBoxList
	
}


/*function getPreparedReplyBody( bodyObject ) {

       bodyObject = bodyObject.clone()

       $('BLOCKQUOTE', bodyObject ).each(function() { $(this).show() })
       $('.showQuotedText', bodyObject ).remove();

        //CONSIDER: allow inline (CID) attchments to be added, strip out img from body otherwise
       $('img', bodyObject).remove()
       //expand show quoted sections
       return html_entity_decode(bodyObject.removeHighlight().html())

 }*/

function getPreparedReplyBody( bodyObject )
{
	//CONSIDER: allow inline (CID) attchments to be added, strip out img from body otherwise
	return $("<div>" + bodyObject.text() + "</div>").find('img').remove().end().html();
}

function normalDate( timeType, dateString )
{
	if(dateString == '')
		return '';

	timeType = Number(timeType);
	
	var finalTimeString = '';
	// generate text for date, based on current date

    try
    {
        tempDate = new Date(dateString);
        temp = tempDate.toTimeString();

        if(temp.indexOf(' ') != -1)
        {
            temp = temp.split(' ');
            temp = temp[0];
        }

        temp = temp.substring(0, temp.length-3);

        year = String(tempDate.getFullYear()).substring(2);

        if( timeType == 2 )
        {
            finalTimeString = tempDate.getDate() + '/' + (tempDate.getMonth() + 1) + '/' + year + ' ' + temp;
        }
        else if( timeType == 3 )
        {
            finalTimeString = (tempDate.getMonth() + 1) + '/' + tempDate.getDate() + '/' + year + ' ' + temp;
        }
    }
    catch( err )
    {
        finalTimeString = '';
    }

    if(finalTimeString == '' || finalTimeString.indexOf('NaN') != -1)
    {
        // something went very wrong..
        finalTimeString = dateString;
    }

	return finalTimeString;
}
