/**
 * Testimonials namespace.
 */
if (typeof Testimonials == "undefined") {

Testimonials = new function() {
    // Properties.
	var url = window.location.protocol + "//www.testimonialdirector.com/";
    var formOptions = [];
    var formInputs = [];
    var insertedJsFiles = [];
    
    // Public.
    this.fetch = function(hash, testimonialsId, options) {
        DomReady.ready(function() {
            // Function parameters.
            if (typeof hash == "undefined") {
                alert("No testimonial hash provided.");
                return;
            }
            
            if (typeof testimonialsId == "undefined") {
                testimonialsId = "testimonials";
            }
            
            if (typeof options == "undefined") {
                options = {};
            }
            
            // Default options.
            options = mergeObject({
                limit: 0,
                r: Math.floor(Math.random()*99999999999),
                customer: "",
                product: "",
                custom: "",
                tid: "",
                loadCss: 1,
                css: "",
                totalId: "",
                scroll: "" }, options);
            
            // Announceable testimonial detection.
            options.aid = getQueryStringByName('aid');
            
            // Query string variables for dynamic testimonials js file.
            var query = {};
            query.h = escape(hash);
            query.d = unescape(window.location.hostname);
            query.div = escape(testimonialsId);
            query.v = escape(window.location.href.slice(window.location.href.indexOf("?") + 1).split("&"));
            query.jquery = escape(getJQueryVersion());
            query.cycle = escape(getJQueryCycleVersion());
            query.jwplayer = escape(getJWPlayerVersion());
            query = mergeObject(query, options);
            
            // Add dyn testimonials js file.
            insertJsFile(url + "get_dyn_testimonials_beta.php?" + createQueryString(query).substring(1));
        });
    };
    
    this.insert = function(testimonials, testimonialsId, branding, affiliator, scroll, media) {
        var affiliateCode = "";
        
        if(affiliator != 0) {
            affiliateCode = "aff/" + affiliator;
        }
        
        document.getElementById(testimonialsId).innerHTML = stripslashes(testimonials);
        
        if (scroll) {
            if (typeof do_scroll == "function") { // Backward compatibility.
                jQuery('#' + testimonialsId + ' .testimonialBlock').show();
                do_scroll();
            } else if (scroll != false) { // New way.
                // Client wants delay to act differently.
                if (typeof scroll.delay != "undefined") {
                    var delay = scroll.delay;
                    scroll.delay = 0;
                    setTimeout(function() { initScroll(testimonialsId, scroll); }, delay);
                } else {
                    initScroll(testimonialsId, scroll);
                }
            }
        }
        
        if (media) {
            initMedia(media);
        }
        
        if (branding == 1) {
            var div = document.createElement("div");
            div.innerHTML = '<div id="' + testimonialsId + '_branding" class="td_branding" style="display: block; clear: both;"><a style="display: inline-block" href="' + url + affiliateCode + '" target="_blank"><img src="' + url + '_img/powered_by.gif" width="173" height="23" alt="Powered by Testimonial Director" border="0" /></a></div>';
            div = div.childNodes[0];
            container = document.getElementById(testimonialsId);
            insertAfter(container, div);
        }
    };
    
    this.insertJsFile = function(file) {
    	var files = [];
    	
    	if (typeof file == 'string') {
    		// Only insert files not previously inserted.
    		if (!inArray(file, insertedJsFiles)) {
    			files.push(file);
    			insertedJsFiles.push(file);
    		}
    	} else if (typeof file == 'object') {
    		for (i in file) {
        		if (typeof file[i] == 'string' /* Mootools fix */ && !inArray(file[i], insertedJsFiles)) {
        			files.push(file[i]);
        			insertedJsFiles.push(file[i]);
        		}
    		}
    	}
    	
    	if (files.length) {
    		var dynamic = url + '_inc/js/dynamicjs.php?';
    		
    		for (i in files) {
    			dynamic += 'file[]=' + escape(files[i]) + '&';
    		}
    		
    		insertJsFile(dynamic.substr(0, dynamic.length - 1));
    	}
    };
    
    this.insertCssFile = function(file) {
        insertCssFile(file);
    };
    
    this.insertCss = function(css) {
        insertCss(css);
    };
    
    this.insertTotal = function(total, totalId) {
        insertTotal(total, totalId);
    };
    
    this.initForm = function(formId, options) {
        DomReady.ready(function() {
            // Function parameters.
            if (typeof formId == "undefined") {
                alert("No form id provided.");
                return;
            }
            
            if(typeof options == "undefined") {
                options = {};
            }
            
            // Form element.
            form = document.getElementById(formId);
            
            if (typeof form == "undefined") {
                alert("No form with id " + formId + " exists.");
                return;
            }
            
            // Default options.
            options = mergeObject({
                loadCss: 1,
                css: "", 
                loadForm: 0,
                language: "",
            	charset: "" 
            }, options);
            
            // Query string variables for init gather form js file.
            var query = {};
            
            if (typeof form.elements['version'] == "undefined") {
                query.version = 1;
            } else {
                query.version = form.elements['version'].value;
            }
            
            query.formId = escape(formId);
            query.hash = escape(form.elements['hash'].value);
            query.account = escape(form.elements['account'].value);
            query.jquery = escape(getJQueryVersion());
            //query.bgiframe = escape(getJQueryBgIframeVersion());
            //query.livequery = escape(getJQueryLivequeryVersion());
            query.facebox = escape(getJQueryFaceboxVersion());
            query.ui = escape(getJQueryUIVersion());
            query.progressbar = escape(getJQueryProgressbarVersion());
            query.swfobject = escape(getSWFObjectVersion());
            query.swfupload = escape(getSWFUploadVersion());
            query.queue = escape(getSWFUploadQueueVersion());
            query.fileprogress = escape(getFileprogressVersion());
            query.charsetDetected = escape(getDocumentCharset());
            query = mergeObject(query, options);
            
            // Add gather form js file.
            insertJsFile(url + "init_gather_form_beta.php?" + createQueryString(query).substring(1));
        });
    };
    
    this.insertForm = function(formId, form) {
		var currentForm = document.getElementById(formId);
		var newForm = document.createElement('div');
		newForm.innerHTML = form;
		newForm = newForm.childNodes[0];
		currentForm.parentNode.replaceChild(newForm, currentForm);
    };
    
    this.validateForm = function(formId, options) {
        if (typeof options == "undefined") {
            options = {};
        }
        
        // Default options.
        options = mergeObject({ error: "You must fill out all of the mandatory fields." }, options);
        
        // Check for missing required fields.
        var required = 0;
        
        jQuery("#" + formId + " .required").each(function() {
            if (jQuery(this).attr("type") == "checkbox") {
                if(!jQuery(this).attr("checked")) {
                    required++;
                }
            } else {
                if(jQuery(this).val() == null || jQuery(this).val() == "" || jQuery(this).val() == "undefined") {
                    required++;
                }
            }
        });
        
        var version = jQuery("#" + formId + " input[name='version']");
        
        if (version.length && version.val() == 2) { // Version 2.
            jQuery.ajax({
                url: url + "_inc/func/validate_media_code_v2.inc.php",
                data: {
                    testimonial_id: formOptions[formId]['testimonialId'],
                    gather_hash: jQuery('#' + formId + ' input[name="hash"]').val()
                },
                dataType: 'jsonp',
                success: function(response) {
                    if (response.error == '1') {
                        required++;
                    }
                    
                    if(required) {
                    	alert(formOptions[formId]['errors']['FORM_MISSING_MANDATORY_FIELDS']);
                    } else {
                        jQuery.ajax({
                            url: url + 'process.php?testimonial_id=' + formOptions[formId]['testimonialId'] + '&callback=?',
                            dataType: 'jsonp',
                            data: jQuery('#' + formId).serialize(),
                            success: function(result) {
                                if (typeof result.error != "undefined") {
                                    alert(result.error);
                                } else {
                                    if (formOptions[formId].type == 'url') {
                                        window.location = result.url;
                                    } else {
                                        //jQuery('#facebox').livequery(function() { $(this).bgiframe(); }); 
                                        jQuery.facebox(formOptions[formId].message);
                                        jQuery(':input', '#' + formId)
                                            .not(':button, :submit, :reset, :hidden')
                                            .val('')
                                            .removeAttr('checked')
                                            .removeAttr('selected');
                                    }
                                }
                            }
                        });
                    }
                }
            });
            
            return false;
        } else { // Version 1.
            if(required) {
                alert(formOptions[formId]['errors']['FORM_MISSING_MANDATORY_FIELDS']);
                return false;
            }
            
            return true;
        }
    };
    
    this.setFormOptions = function(formId, options) {
        formOptions[formId] = options;
    };
    
    this.initUploadInput = function(placeholderId, options) {
        // Wait until SWFUpload has loaded (async).
        if (!getSWFUploadQueueVersion()) {
            setTimeout(function() { Testimonials.initUploadInput(placeholderId, options); }, 100);
            return;
        }
        
        jQuery('.' + placeholderId).html('<div id="' + placeholderId + '"></div>');
        jQuery('#' + placeholderId).after(
            "<div id='" + placeholderId + "_progressbar' class='progressBar'></div>" + 
            "<input style='display:none;' id='" + placeholderId + "_btnCancel' type='button' value='Cancel' onclick='cancelQueue(Testimonials.formInputs[\"" + placeholderId + "\"]);' disabled='disabled' />" + 
            "<div id='" + placeholderId + "_fsUploadProgress'></div>"
        );
        
        formInputs[placeholderId] = new SWFUpload({
            upload_url: url + "_inc/func/add_testimonial_code.inc.php",
            post_params: {
                "PHPSESSID": options.sessionId,
                //"IMAGELINEID": "5",
                "IMAGENAME": options.imageName,
                "CURRENTTESIID": options.testimonialId,
                "DEFINEMEDIAID": options.mediaId,
                "MEDIATYPE": options.mediaType
            },
            file_size_limit: options.fileSizeLimit,
            file_types: options.fileTypes,
            file_types_description: options.fileTypesDesc,
            file_upload_limit: options.fileUploadLimit,
            file_queue_limit: options.fileQueueLimit,
            file_dialog_start_handler: fileDialogStart,
            file_queued_handler: fileQueued,
            file_queue_error_handler: fileQueueError,
            file_dialog_complete_handler: fileDialogComplete,
            upload_start_handler: uploadStart,
            upload_progress_handler: uploadProgress,
            upload_error_handler: uploadError,
            upload_success_handler: uploadSuccess,
            upload_complete_handler: uploadComplete,
            button_image_url: url + "_inc/flash/locale/" + options.language + "/upload.png",
            button_placeholder_id: placeholderId,
            button_width: 61,
            button_height: 22,
            moving_average_history_size: 40,
            flash_url: url + "_inc/flash/Flash/swfupload.swf",
            swfupload_element_id: "flashUI", // Setting from graceful degradation plugin
            degraded_element_id: "degradedUI", // Setting from graceful degradation plugin
            custom_settings: {
                progressTarget: placeholderId + "_fsUploadProgress",
                testimonialID: options.testimonialId,
                progressbar: placeholderId + "_progressbar",
                cancelButtonId: placeholderId + "_btnCancel"
            },
            debug: false
        });
    };
    
    this.initStreamInput = function(placeholderId, options) {
        // Wait until SWFObject has loaded (async).
        if (!getSWFObjectVersion()) {
            setTimeout(function() { Testimonials.initStreamInput(placeholderId, options); }, 100);
            return;
        }
        
        if (typeof options == "undefined") {
            options = formInputs[placeholderId];
        } else {
            formInputs[placeholderId] = options;
        }
        
        jQuery('.' + placeholderId).html('<div id="' + placeholderId + '"></div>');
        swfobject.embedSWF(url + options.recorderSwf, placeholderId, options.recorderWidth, options.recorderHeight, options.flash, null, { placeholderId: placeholderId, version: options.version, language: options.language, hasFont: options.hasFont, instructionsText: options.locale.INSTRUCTIONS, reviewButtonText: options.locale.REVIEW_BUTTON, recordButtonText: options.locale.RECORD_BUTTON }, { allowScriptAccess : 'always', quality : 'high' });
        
        // Firefox Mac fix related to the flash object.
        try {
            if (jQuery.browser.mozilla && Math.floor(window.mozInnerScreenX) != window.mozInnerScreenX ) {
                jQuery('#' . placeholderId).css('margin-left' , '0.5px');
            }
        } catch(ex) {
            
        }
    };
    
    this.initVideoPlayer = function(placeholderId, streamedFile) {
        options = formInputs[placeholderId];
        jQuery('#' + placeholderId).replaceWith('<p id="' + placeholderId + '">' + options.locale.RENDERING + '</p>');
        jQuery.ajax({
            url: url + '_inc/functions.inc.php?callback=?',
            dataType: 'jsonp',
            data: { currentAction: 'saveRecordedVideo', t: options.testimonialId, h: options.hash, f: streamedFile, version: options.version },
            success: function(response) {
                swfobject.embedSWF(url + options.playerSwf, placeholderId, options.playerWidth, options.playerHeight, options.flash, null, { v: response.file, placeholderId: placeholderId, version: options.version, language: options.language, hasFont: options.hasFont, recordingSavedText: options.locale.RECORDING_SAVED, rerecordButtonText: options.locale.RERECORD_BUTTON, saveButtonText: options.locale.SAVE_BUTTON }, { allowScriptAccess : 'always', quality : 'high' });
            }
        });
    };
    
    this.initAudioPlayer = function(placeholderId, streamedFile) {
        options = formInputs[placeholderId];
        jQuery('#' + placeholderId).replaceWith('<p id="' + placeholderId + '">' + options.locale.RENDERING + '</p>');
        jQuery.ajax({
            url: url + '_inc/functions.inc.php?callback=?',
            dataType: 'jsonp',
            data: { currentAction: 'saveRecordedAudio', t: options.testimonialId, h: options.hash, f: streamedFile, version: options.version },
            success: function(response) {
                swfobject.embedSWF(url + options.playerSwf, placeholderId, options.playerWidth, options.playerHeight, options.flash, null, { file : response.file }, { allowScriptAccess : 'always', quality : 'high' });
            }
        });
    };
    
    // Private.
    var inArray = function(needle, haystack) {
        var length = haystack.length;
        
        for(var i = 0; i < length; i++) {
            if(haystack[i] == needle) return true;
        }
        
        return false;
    };
    
    var insertJsFile = function(file) {
        script = document.createElement("script");
        script.type = "text/javascript";
        script.src = file;
        script = eval(script);
        document.body.appendChild(script);
    };
    
    var insertCssFile = function(file) {
        link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = file;
        document.body.appendChild(link);
    };
    
    var insertCss = function(css) {
        // http://stackoverflow.com/questions/524696
        var div = document.createElement("div");
        div.innerHTML = "<br>" + css; // Yes, the <br> is necessary (IE 7).
        document.body.appendChild(div);
    };
    
    var insertTotal = function(total, totalId) {
        document.getElementById(totalId).innerHTML = total;
    };
    
    var initScroll = function(testimonialsId, options) {
        // Wait until JQuery has loaded (async).
        if (typeof jQuery != "function" || typeof jQuery().cycle != "function") {
            setTimeout(function() { initScroll(testimonialsId, options); }, 100);
            return;
        }
        
        // Default options.
        options = mergeObject({ 
            fx: "fade", 
            containerResize: 0, 
            //before: onBefore,
            cleartypeNoBg: false,
            timeout: 6000, 
            speed: 500 }, options);
        
        if (options.containerResize == 0) {
            options.before = onBefore;
        }
        
        options.timeout = Number(options.timeout);
        options.speed = Number(options.speed);
        jQuery('#' + testimonialsId + ' .testimonialBlock').show();
        jQuery("#" + testimonialsId + " .testimonialBlock").cycle(options);
    };
    
    var onBefore = function(currSlideElement, nextSlideElement, options, forwardFlag){
        var ht = jQuery(nextSlideElement).outerHeight(true);
        jQuery(this).parent().css("height", ht);
    };
    
    var initMedia = function(media) {
        // Wait until jwplayer has loaded (async).
        if (!getJWPlayerVersion()) {
            setTimeout(function() { initMedia(media); }, 100);
            return;
        }
        
        for (i in media) {
            jwplayer(i).setup(media[i]);
        }
    };
    
    var insertAfter = function(referenceNode, newNode) {
        // http://www.netlobo.com/media/examples/insertAfter.html
        referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    };
    
    var mergeObject = function(object1, object2) {
        for (var i in object2) {
            object1[i] = object2[i];
        }
        
        return object1;
    };
    
    var createQueryString = function(param, prefix) {
        var queryString = '';
        
        if (typeof prefix == "undefined") {
            prefix = '';
        }
        
        for (var i in param) {
            if (typeof param[i] == "object") {
                queryString += createQueryString(param[i], prefix + (prefix ? '[' : '') + i + (prefix ? ']' : ''));
            } else {
                queryString += '&' + prefix + (prefix ? '[' : '') + i + (prefix ? ']' : '') + "=" + param[i];
            }
        }
        
        return queryString;
    };
    
    var getJQueryVersion = function() {
        var version = "";
        
        if (typeof jQuery == "function"){
            version = jQuery().jquery;
            
            if (version == "$Rev: 509 $") {
                version = "1.0.0";
            }
        }
        
        return version;
    };
    
    var getJQueryCycleVersion = function() {
        var version = "";
        
        if (typeof jQuery == "function" && typeof jQuery().cycle == "function"){
            version = jQuery.fn.cycle.ver();
        }
        
        return version;
    };
    
    var getJQueryBgIframeVersion = function() {
        var version = "";
        
        if (typeof jQuery == "function" && typeof jQuery().bgiframe == "function"){
            version = 1;
        }
        
        return version;
    };
    
    var getJQueryLivequeryVersion = function() {
        var version = "";
        
        if (typeof jQuery == "function" && typeof jQuery().livequery == "function"){
            version = 1;
        }
        
        return version;
    };
    
    var getJQueryFaceboxVersion = function() {
        var version = "";
        
        if (typeof jQuery == "function" && typeof jQuery().facebox == "function"){
            version = 1; // There is no way to detect the version, just whether it exists or not.
        }
        
        return version;
    };
    
    var getJQueryUIVersion = function() {
        var version = "";
        
        if (typeof jQuery == "function" && typeof jQuery.ui == "object"){
            version = jQuery.ui.version;
        }
        
        return version;
    };
    
    var getJQueryProgressbarVersion = function() {
        var version = "";
        
        if (typeof jQuery == "function" && typeof jQuery.ui == "object" && typeof jQuery.ui.progressbar == "function") {
            version = jQuery.ui.progressbar.version;
        }
        
        return version;
    };
    
    var getSWFObjectVersion = function() {
        var version = "";
        
        if (typeof swfobject == "object"){
            version = 1; // There is no way to detect the version, just whether it exists or not.
        }
        
        return version;
    };
    
    var getSWFUploadVersion = function() {
        var version = "";
        
        if (typeof SWFUpload == "function"){
            version = SWFUpload.version;
        }
        
        return version;
    };
    
    var getSWFUploadQueueVersion = function() {
        var version = "";
        
        if (typeof SWFUpload == "function" && typeof SWFUpload.queue == "object"){
            version = 1; // There is no way to detect the version, just whether it exists or not.
        }
        
        return version;
    };
    
    var getJWPlayerVersion = function() {
        var version = "";
        
        if (typeof jwplayer == "function"){
            version = jwplayer.version;
        }
        
        return version;
    };
    
    var getFileprogressVersion = function() {
        var version = "";
        
        if (typeof FileProgress == "function"){
            version = 1; // There is no way to detect the version, just whether it exists or not.
        }
        
        return version;
    };
    
    var getQueryStringByName = function(name) {
        // http://stackoverflow.com/questions/901115/get-querystring-values-with-jquery
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    };
    
    var getDocumentCharset = function() {
    	return (document.characterSet ? document.characterSet : document.charset).toUpperCase();
    };
};

/**
 * Legacy code.
 */
function show_testimonials(txt, div_id, branding, affiliator, scroll) {

}

function get_testimonials(hash) {
	host = unescape(window.location.hostname);
	/*
	www = host.substr(0,4);
	if(www != "www.") {
		host = "www."+host;
	}
	*/
	if(undefined == window.r) {
		r = 0;
	}
	
	if(undefined == window.cat) {
		cat = 0;
	}
	
	if(undefined == window.prod) {
		prod = 0;
	}
	
	if(undefined == window.tid) {
		tid = 0;
	}
	
	if(typeof site_url == "undefined") {
		site_url = "https://www.testimonialdirector.com";
	}
	
	var script= document.createElement('script');
	var url_vars = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	script.type= "text/javascript";
	script.src=site_url+"/get_dyn_testimonials.php?h="+hash+"&d="+host+"&v="+url_vars+"&r="+r+"&cat="+cat+"&prod="+prod+"&tid="+tid;
	document.body.appendChild(script);
}

function get_testimonial_data(hash,div_id,limit) {
    if(undefined == window.r) {
        r = 0;
    }
    
    if(undefined == window.cat) {
        cat = 0;
    }
    
    if(undefined == window.prod) {
        prod = 0;
    }
    
    if(undefined == window.tid) {
        tid = 0;
    }
    
    if(typeof limit == "undefined") {
        limit = "no";
    }
    
    Testimonials.fetch(hash, div_id, { limit:limit, r:r, customer:cat, product:prod, tid:tid, loadCss:0 });
}

function get_testimonial_data_return(hash, div_id, limit, r, cat, prod, tid) {
    Testimonials.fetch(hash, div_id, { limit:limit, r:r, customer:cat, product:prod, tid:tid, loadCss:0 });
}

function concatObject(obj) {
  str='';
  for(prop in obj)
  {
    str+=prop + ": "+ obj[prop]+"\n";
  }
  return(str);
}

function updateComments(txt) {
	document.getElementById(div_id).innerHTML = txt;
    
	if(typeof do_scroll == 'function') {
		do_scroll();
	} 
}

function addslashes(str) {
    str=str.replace(/\\/g,'\\\\');
    str=str.replace(/\'/g,'\\\'');
    str=str.replace(/\"/g,'\\"');
    str=str.replace(/\0/g,'\\0');
    return str;
}

function stripslashes(str) {
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\0/g,'\0');
    str=str.replace(/\\\\/g,'\\');
    return str;
}

(function(){

    var DomReady = window.DomReady = {};

	// Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery. 

    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used
    var browser = {
    	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    	safari: /webkit/.test(userAgent),
    	opera: /opera/.test(userAgent),
    	msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
    	mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
    };    

	var readyBound = false;	
	var isReady = false;
	var readyList = [];

	// Handle when the DOM is ready
	function domReady() {
		// Make sure that the DOM is not already loaded
		if(!isReady) {
			// Remember that the DOM is ready
			isReady = true;
            
	        if(readyList) {
	            for(var fn = 0; fn < readyList.length; fn++) {
	                readyList[fn].call(window, []);
	            }
                
	            readyList = [];
	        }
		}
	};

	// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.
	function addLoadEvent(func) {
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      if (oldonload) {
	        oldonload();
	      }
	      func();
	    }
	  }
	};

	// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
	function bindReady() {
		if(readyBound) {
		    return;
	    }
	
		readyBound = true;

		// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
		if (document.addEventListener && !browser.opera) {
			// Use the handy event callback
			document.addEventListener("DOMContentLoaded", domReady, false);
		}

		// If IE is used and is not in a frame
		// Continually check to see if the document is ready
		if (browser.msie && window == top) (function(){
			if (isReady) return;
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch(error) {
				setTimeout(arguments.callee, 0);
				return;
			}
			// and execute any waiting functions
		    domReady();
		})();

		if(browser.opera) {
			document.addEventListener( "DOMContentLoaded", function () {
				if (isReady) return;
				for (var i = 0; i < document.styleSheets.length; i++)
					if (document.styleSheets[i].disabled) {
						setTimeout( arguments.callee, 0 );
						return;
					}
				// and execute any waiting functions
	            domReady();
			}, false);
		}

		if(browser.safari) {
		    var numStyles;
			(function(){
				if (isReady) return;
				if (document.readyState != "loaded" && document.readyState != "complete") {
					setTimeout( arguments.callee, 0 );
					return;
				}
				if (numStyles === undefined) {
	                var links = document.getElementsByTagName("link");
	                for (var i=0; i < links.length; i++) {
	                	if(links[i].getAttribute('rel') == 'stylesheet') {
	                	    numStyles++;
	                	}
	                }
	                var styles = document.getElementsByTagName("style");
	                numStyles += styles.length;
				}
				if (document.styleSheets.length != numStyles) {
					setTimeout( arguments.callee, 0 );
					return;
				}
			
				// and execute any waiting functions
				domReady();
			})();
		}

		// A fallback to window.onload, that will always work
	    addLoadEvent(domReady);
	};

	// This is the public function that people can use to hook up ready.
	DomReady.ready = function(fn, args) {
		// Attach the listeners
		bindReady();
    
		// If the DOM is already ready
		if (isReady) {
			// Execute the function immediately
			fn.call(window, []);
	    } else {
			// Add the function to the wait list
	        readyList.push( function() { return fn.call(window, []); } );
	    }
	};
    
	bindReady();
	
})();

}

