/* 
	When this script is loaded it appends five methods to the retouch_box object
	
		- injectDOMelements :: This method creates the html node structure for both the 'bar' and the 'box', it also does all of the 
								css editing that's necessary to center everything etc. 
		
		- showBar :: This method shows the 'bar' after a delay which is declared at the client (retouch_box.delay)
		
		- load :: 	This method points the source of the iframe to the url declared at the client (retouch_box.url).
					it also calculates the width og the browser and box to position it properly. it also applies crossbrowser
					opacity to the overlay & bar. 

		- done :: 	This method is called on the load event of the iframe. it fades in the overlay and the box and slide the bar up.

		- close :: 	This method is called when the users clicks outside the box or clics the span with the 
					class close. It fades out the box and overlay.
	
	When the script is done loading it invokes the injectDOMelements and showBar methods to get the show started. 
	
*/
/* function that detects the version of internet explorer
   it Returns the version of Internet Explorer or a -1 */

/**
* Copyright (c) 2005 - 2009, James Auldridge
* All rights reserved.
*
* Licensed under the BSD, MIT, and GPL (your choice!) Licenses:
*  http://code.google.com/p/cookies/wiki/License
*
*/
var jaaulde = window.jaaulde || {}; jaaulde.utils = jaaulde.utils || {}; jaaulde.utils.cookies = (function() {
    var cookies = []; var defaultOptions = { hoursToLive: null, path: '/', domain: null, secure: false }; var resolveOptions = function(options) {
        var returnValue; if (typeof options !== 'object' || options === null)
        { returnValue = defaultOptions; }
        else
        { returnValue = { hoursToLive: (typeof options.hoursToLive === 'number' && options.hoursToLive !== 0 ? options.hoursToLive : defaultOptions.hoursToLive), path: (typeof options.path === 'string' && options.path !== '' ? options.path : defaultOptions.path), domain: (typeof options.domain === 'string' && options.domain !== '' ? options.domain : defaultOptions.domain), secure: (typeof options.secure === 'boolean' && options.secure ? options.secure : defaultOptions.secure) }; }
        return returnValue;
    }; var expiresGMTString = function(hoursToLive)
    { var dateObject = new Date(); dateObject.setTime(dateObject.getTime() + (hoursToLive * 60 * 60 * 1000)); return dateObject.toGMTString(); }; var assembleOptionsString = function(options) {
        options = resolveOptions(options); return ((typeof options.hoursToLive === 'number' ? '; expires=' + expiresGMTString(options.hoursToLive) : '') + '; path=' + options.path +
(typeof options.domain === 'string' ? '; domain=' + options.domain : '') +
(options.secure === true ? '; secure' : ''));
    }; var splitCookies = function() {
        cookies = {}; var pair, name, value, separated = document.cookie.split(';'); for (var i = 0; i < separated.length; i = i + 1)
        { pair = separated[i].split('='); name = pair[0].replace(/^\s*/, '').replace(/\s*$/, ''); value = decodeURIComponent(pair[1]); cookies[name] = value; }
        return cookies;
    }; var constructor = function() { }; constructor.prototype.get = function(cookieName) {
        var returnValue; splitCookies(); if (typeof cookieName === 'string')
        { returnValue = (typeof cookies[cookieName] !== 'undefined') ? cookies[cookieName] : null; }
        else if (typeof cookieName === 'object' && cookieName !== null) {
            returnValue = {}; for (var item in cookieName) {
                if (typeof cookies[cookieName[item]] !== 'undefined')
                { returnValue[cookieName[item]] = cookies[cookieName[item]]; }
                else
                { returnValue[cookieName[item]] = null; } 
            } 
        }
        else
        { returnValue = cookies; }
        return returnValue;
    }; constructor.prototype.filter = function(cookieNameRegExp) {
        var returnValue = {}; splitCookies(); if (typeof cookieNameRegExp === 'string')
        { cookieNameRegExp = new RegExp(cookieNameRegExp); }
        for (var cookieName in cookies) {
            if (cookieName.match(cookieNameRegExp))
            { returnValue[cookieName] = cookies[cookieName]; } 
        }
        return returnValue;
    }; constructor.prototype.set = function(cookieName, value, options) {
        if (typeof value === 'undefined' || value === null) {
            if (typeof options !== 'object' || options === null)
            { options = {}; }
            value = ''; options.hoursToLive = -8760;
        }
        var optionsString = assembleOptionsString(options); document.cookie = cookieName + '=' + encodeURIComponent(value) + optionsString;
    }; constructor.prototype.del = function(cookieName, options) {
        var allCookies = {}; if (typeof options !== 'object' || options === null)
        { options = {}; }
        if (typeof cookieName === 'boolean' && cookieName === true)
        { allCookies = this.get(); }
        else if (typeof cookieName === 'string')
        { allCookies[cookieName] = true; }
        for (var name in allCookies) {
            if (typeof name === 'string' && name !== '')
            { this.set(name, null, options); } 
        } 
    }; constructor.prototype.test = function() {
        var returnValue = false, testName = 'cT', testValue = 'data'; this.set(testName, testValue); if (this.get(testName) === testValue)
        { this.del(testName); returnValue = true; }
        return returnValue;
    }; constructor.prototype.setOptions = function(options) {
        if (typeof options !== 'object')
        { options = null; }
        defaultOptions = resolveOptions(options);
    }; return new constructor();
})(); (function() {
    if (window.jQuery) {
        (function(jQuery) {
            jQuery.cookies = jaaulde.utils.cookies; var extensions = { cookify: function(options) {
                return this.each(function() {
                    var i, resolvedName = false, resolvedValue = false, name = '', value = '', nameAttrs = ['name', 'id'], nodeName, inputType; for (i in nameAttrs) {
                        if (!isNaN(i)) {
                            name = jQuery(this).attr(nameAttrs[i]); if (typeof name === 'string' && name !== '')
                            { resolvedName = true; break; } 
                        } 
                    }
                    if (resolvedName) {
                        nodeName = this.nodeName.toLowerCase(); if (nodeName !== 'input' && nodeName !== 'textarea' && nodeName !== 'select' && nodeName !== 'img')
                        { value = jQuery(this).html(); resolvedValue = true; }
                        else {
                            inputType = jQuery(this).attr('type'); if (typeof inputType === 'string' && inputType !== '')
                            { inputType = inputType.toLowerCase(); }
                            if (inputType !== 'radio' && inputType !== 'checkbox')
                            { value = jQuery(this).val(); resolvedValue = true; } 
                        }
                        if (resolvedValue) {
                            if (typeof value !== 'string' || value === '')
                            { value = null; }
                            jQuery.cookies.set(name, value, options);
                        } 
                    } 
                });
            }, cookieFill: function() {
                return this.each(function() {
                    var i, resolvedName = false, name = '', value, nameAttrs = ['name', 'id'], iteration = 0, nodeName; for (i in nameAttrs) {
                        if (!isNaN(i)) {
                            name = jQuery(this).attr(nameAttrs[i]); if (typeof name === 'string' && name !== '')
                            { resolvedName = true; break; } 
                        } 
                    }
                    if (resolvedName) {
                        value = jQuery.cookies.get(name); if (value !== null) {
                            nodeName = this.nodeName.toLowerCase(); if (nodeName === 'input' || nodeName === 'textarea' || nodeName === 'select')
                            { jQuery(this).val(value); }
                            else
                            { jQuery(this).html(value); } 
                        } 
                    }
                    iteration = 0;
                });
            }, cookieBind: function(options) {
                return this.each(function() {
                    jQuery(this).cookieFill().change(function()
                    { jQuery(this).cookify(options); });
                });
            } 
            }; jQuery.each(extensions, function(i)
            { jQuery.fn[i] = this; });
        })(window.jQuery);
    }
})();

function setCookie() {
    jQuery.cookies.set(retouch_box.key, 'false', { hoursToLive: 86807.8 });
}
   
function getInternetExplorerVersion()
{
  var rv = -1; // Return value assumes failure.
  
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  } else {
	rv = 1000;  
  }
  return rv;
}

 
var ver = getInternetExplorerVersion();
if ( ver <= 6) {
		// don't do anything if it's ie6 -- it's still broken :-(
} else {



retouch_box.injectDOMelements = function() {

    jQuery('body')
		.prepend('<div id="controllers">' + 
								'<a href="#" id="closeimg_bar_link">' +
									'<img id="closeimg_bar" src="http://services.mailiac.com/campaignscript/ver1/images/close_bar.png" width="20px" height="14px"/>' +
									retouch_box.bar.closetext + 
								'</a>' +
								'<a href="javascript:void(0)" id="showlater_button">'+ 
									'<img src="http://services.mailiac.com/campaignscript/ver1/images/remind-me-later.png" width="20px" height="14px" />'+ 
									retouch_box.bar.remindmelatertext +
								'</a>'+
							'</div>');
    // The html node structure for the bar
    jQuery('body')
		.prepend('<div id="retouch_bar" style="display:none">' +
					'<center><img id="barimage" src="' + retouch_box.bar.imageurl + '"/></center>' +
				'</div>')

    // The html node structure for the overlay. 
		.prepend('<div id="retouch_overlay" style="display:none"></div>')

    // The html node structure for the retouch_box 
		.prepend('<div id="retouch_main" style="display:none">' +
	            	'<span class="retouch_close"><img id="closeimg" src="http://services.mailiac.com/campaign/images/close-old.png"/></span>' +
					'<img src="http://services.mailiac.com/campaign/images/ajax-loader.gif" id="retouch_loader"/>' +
					'<iframe src="" id="retouch_iframe" width="' + retouch_box.iframe.width + 'px" height="' + retouch_box.iframe.height + 'px" frameborder="0" scrolling="no" allowTransparency="true"></iframe>' +
	        	'</div>'
	);

    // make sure that the div#retouch_main can contain the iframe, 
    // without adding any whitespace around it. 
    jQuery('#retouch_main').css({
        'height': retouch_box.iframe.height,
        'width': retouch_box.iframe.width
    });

    // the iframe shouldn't be visible before is has loaded the file.
    jQuery('#retouch_iframe').css('opacity', 0);

    var leftOffsetLoader = (retouch_box.iframe.width / 2) - 100;
    var topOffsetLoader = retouch_box.iframe.height / 2 - 100;

    // position the retouch-loader (the .gif image)
    jQuery('#retouch_loader').css({
        'position': 'absolute',
        'left': leftOffsetLoader,
        'top': topOffsetLoader

    });

    // Position the close button in the bar
    var topOffsetCloseImgbar = retouch_box.bar.height - 30;
		jQuery('#controllers').css({ 
			'display' : 'none',
			'width' : retouch_box.bar.controller.width,
			'left' : jQuery(document).width() - retouch_box.bar.controller.width,
			'top' : retouch_box.bar.height ,
			'z-index': 10000,
			'background' : retouch_box.bar.colour
		});
		jQuery('#controllers a').css({ 
			'color' : retouch_box.bar.controller.linkcolour
		});

    // Hide the bar
    jQuery('#closeimg_bar_link').bind('click', function() {
        retouch_box.hideBar();
        jQuery.cookies.set(retouch_box.key, 'false', { hoursToLive: 86807.8 });
    });

    // Hide the bar
    jQuery('#showlater_button').bind('click', function() {
        retouch_box.hideBar();
        jQuery.cookies.set(retouch_box.key, 'false', { hoursToLive: 0.015 });
    });

    // Position the close button in the top-right corner
    var leftOffsetCloseImg = retouch_box.iframe.width - 15;
    jQuery('#closeimg').css({
        'position': 'absolute',
        'left': leftOffsetCloseImg,
        'top': '-15px'
    });

		/*		jQuery('#retouch_bar').hover(
					function(){ jQuery('#controllers').slideDown(400); },
					function(){ jQuery('#controllers').slideUp(400); }
				);*/

	/*
		arrange the 
	*/
	retouch_box.rearrange_retouch_main();
	jQuery(window).bind('resize', function() {
		retouch_box.rearrange_retouch_main();
	});
    /*
    Sets the opacity of the overlay to 0.8 in all browsers. 
    */
    jQuery('#retouch_overlay').css('opacity', 0.8);

}

retouch_box.rearrange_retouch_main = function(){
	/*
    Few calculations to makes sure the retouch_box is positioned properly.
    */

    var docWidth = jQuery(document).width() / 2;
    var docHeight = jQuery(document).height() / 2;
    var boxWidth = jQuery('#retouch_main').width() / 2;
    var boxHeight = jQuery('#retouch_main').height() / 2;

    jQuery('#retouch_main').css({
        'left': docWidth - boxWidth,
        'top': 10,
        'border': retouch_box.iframe.border
    });
		jQuery('#controllers').css({
			'left' : jQuery(document).width() - retouch_box.bar.controller.width
		});
}

retouch_box.showBar = function(){
	/* 	when the time declared at the client has passed it invokes the anonymous function. 
		the function edits some css attributes depending on what position the user has chosen, 
		slides down the bar and binds the load() method to the click event. 
	*/

	
	
		jQuery('#retouch_bar').css({
			'position' : 'fixed',	
			'opacity': retouch_box.bar.opacity
		});
	
		var position = retouch_box.bar.position;
		switch(position) {
			case "bottom":
			case "top": 
				jQuery('#retouch_bar').css({
					'left' : 0,
					'height' : retouch_box.bar.height,
					'width' : '100%',
					'background' : retouch_box.bar.colour			
				}).css(retouch_box.bar.position,0);
			; break;
			case "center": 
				/* code here*/
			; break;
		}
			
		jQuery('#retouch_bar')
		.slideDown(500, function(){
		    jQuery('#controllers').slideDown(400);
		})
		.bind('click', retouch_box.load );		
		
		
}

retouch_box.hideBar = function(){
	jQuery('#controllers').slideUp(200);
	jQuery('#retouch_bar').slideUp(500);
}

retouch_box.load = function(){
	
	/*
		Binds the done() method to the load event of the iframe in all browsers.
		Apparently jquery doesn't support this :(
	*/
	if (document.getElementById('retouch_iframe').getAttribute("src") == "") {
	      if (document.getElementById('retouch_iframe').attachEvent) { // IE
	        //detachEvent("onload", retouch_box.done);
	        document.getElementById('retouch_iframe').attachEvent("onload", retouch_box.done);
	      } else if (document.getElementById('retouch_iframe').addEventListener) { // Mozilla
	        document.getElementById('retouch_iframe').addEventListener("load", retouch_box.done, false);
	      } 
	    }
	
	/*
		When 1 sec have passed it changes the source of the iframe to the 
		url declared at the client.		
	*/
	setTimeout(function(){
		jQuery('#retouch_iframe').attr('src',retouch_box.iframe.url);
	}, 1000)
	
	/*
		Fades in the overlay and the box. also fades out the bar. 
	*/
	jQuery('#retouch_overlay').fadeIn(300, function(){
		jQuery('#retouch_main').fadeIn(500);
		retouch_box.hideBar();
	});
		
}

retouch_box.done = function(){
	
	/*
		Fades out the loader and fades in the iframe. 
	*/
	
	jQuery('#retouch_loader').fadeOut(300, function(){
		jQuery('#retouch_iframe').css('opacity','1'); 
	});
	
	/*
		Binds the close() method to the click event of both the overlay & span.retouch_close.
	*/
	jQuery('#retouch_overlay, span.retouch_close').bind('click', retouch_box.close );
}

retouch_box.close = function(){
	
	/*
		Fades out the box, then the overlay.
	*/
	jQuery('#retouch_main').fadeOut(500, function(){
		jQuery('#retouch_overlay').fadeOut(300);
	});
}

retouch_box.refresh = function(){
	/*
		This function is used when testing, it deletes the retouch_box and creates a new one
		with the opdated values. 
	*/
	jQuery('#retouch_bar, #retouch_overlay, #retouch_main' ).remove();
	this.injectDOMelements();
	if (retouch_box.bar.autoDisplay) {
		setTimeout(function(){
			retouch_box.showBar();
		}, retouch_box.bar.delay);
	}
	
}

retouch_box.injectDOMelements();
if (retouch_box.bar.autoDisplay && jQuery.cookies.get(retouch_box.key) != "false" && jQuery.cookies.test()) {
	setTimeout(function(){
		retouch_box.showBar();
	}, retouch_box.bar.delay);
}
} // end of ie if-clause