var WhoSayPhotoEmbed = (function () {
  var jQueryCallbacks = [];
	var cssIncluded = false;

	var markup = {
	 sidebar: '<div class="back" style=""><div class="photo"><a href="" title="" target="_blank"><img src=""  alt="" width=""  height=""/></a></div><div class="footer"><span><a target="_blank" href="http://www.whosay.com/" title="WhoSay" class="whosay-logo-link">WhoSay</a></span><span class="morelink"><a target="_blank" href=""><span class="moreText"></span>&nbsp;&raquo;</a></span></div></div>'     
	};

	return {
		create: function (settings) {

			var scriptPath = "";
			var scriptEls = document.getElementsByTagName('script');
			for( var i = 0; i < scriptEls.length; ++i ) {
				var scriptSrc = scriptEls[i].src;
				if( /photoEmbedWidget\.js$/.test(scriptSrc) ) {
					scriptPath = scriptSrc.substr( 0, scriptSrc.lastIndexOf('/')+1 );
					break;
				}
			}
			
			var cssUrl = scriptPath + 'styles.css';
			var settings, container, data;

			function trace(message) {
				if (window.console && settings.debug)
					window.console.log('WhoSayPhotoEmbed Widget: ' + message);
			}

			function includeCss() {
				if (!cssIncluded) {
					var link = document.createElement('link');
					link.setAttribute('type', 'text/css');
					link.setAttribute('rel', 'stylesheet');
					link.setAttribute('href', cssUrl);

					var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
					head.insertBefore(link, head.firstChild);

					cssIncluded = true;
				}
			}

			function prepareContainer() {
				if (settings.containerId) {
					container = document.getElementById(settings.containerId);
				} else if (document.readyState !== "complete") {
					var containerId = 'WhoSayPhotoEmbed_' + Math.ceil(Math.random() * 1000);
					document.write('<div id="' + containerId + '"></div>');
					container = document.getElementById(containerId);
				} else {
					trace('DOM is ready, but containerId is missing');
				}

				if (container)
					container.className = 'WhoSayPhotoEmbed';

				return !!container;
			}

      function checkSettingValueByParam(settingName) {
        var defaultValue;
        if(settingName == 'title') defaultValue = (settings[settingName] || 'none').toLowerCase();
        if(settingName == 'vanityRoot') defaultValue = (settings[settingName] || '').toLowerCase();
        if(settingName == 'photoId') defaultValue = (settings[settingName] || '').toLowerCase();
        if(settingName == 'width') defaultValue = (settings[settingName] || '644').toLowerCase();
        if(settingName == 'height') defaultValue = (settings[settingName] || '473').toLowerCase();
        if(settingName == 'vanityRoot') defaultValue = (settings[settingName] || '').toLowerCase();
        if(settingName == 'vanityLink') defaultValue = (settings[settingName] || '').toLowerCase();
        if(settingName == 'clientName') defaultValue = (settings[settingName] || '');
        
        return defaultValue;
      }

			function render() {
  		    var viewName = 'sidebar';
          var title = checkSettingValueByParam('title');
          var vanityRoot = checkSettingValueByParam('vanityRoot');
          var photoId = checkSettingValueByParam('photoId');
          var width = checkSettingValueByParam('width');
          var height = checkSettingValueByParam('height');
          var totHeight = parseInt(height) + 46;
          var vanityLink = checkSettingValueByParam('vanityLink');
          var clientName = checkSettingValueByParam('clientName');

					WhoSayPhotoEmbed.jQuery(container)
						.html(markup[viewName])
						.find('.back').attr('style', 'width:'+width+'px'+';height:'+ totHeight + 'px').end();

					WhoSayPhotoEmbed.jQuery(container)
					 .find('.photo a').attr('href', vanityLink ).attr('title', title ).end();
          WhoSayPhotoEmbed.jQuery(container)
            .find('.photo img').attr('src', photoId ).attr('width', width + 'px').attr('height', height + 'px' ).end();
          WhoSayPhotoEmbed.jQuery(container)
            .find('.morelink a').attr('href', vanityRoot ).end();
          WhoSayPhotoEmbed.jQuery(container)
            .find('.morelink .moreText').text('More from ' + clientName ).end();
				 
			}


			if (!settings.vanityRoot) {
				trace('vanityRoot is not defined');
				return;
			}

			if (!prepareContainer())
				return;

			includeCss();

			this.loadJQuery(render);
		},
    loadJQuery: function (callback) {
      if (!!WhoSayPhotoEmbed.jQuery) {
        if (WhoSayPhotoEmbed.jQuery.isFunction(callback))
          callback();
      } else if (typeof jQuery != 'undefined' && typeof jQuery.Deferred != 'undefined') {
        WhoSayPhotoEmbed.jQuery = jQuery;
        if (WhoSayPhotoEmbed.jQuery.isFunction(callback))
          callback();
      } else {
        jQueryCallbacks.push(callback);

        if (jQueryCallbacks.length == 1) {
          var script = document.createElement("script");
          script.async = 'async';
          script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js';

          script.onload = script.onreadystatechange = function () {
            if (!script.readyState || /loaded|complete/.test(script.readyState)) {
              script.onload = script.onreadystatechange = null;
              if (head && script.parentNode)
                head.removeChild(script);
              script = undefined;
              
              WhoSayPhotoEmbed.jQuery = jQuery.noConflict(true);
              WhoSayPhotoEmbed.jQuery.each(jQueryCallbacks, function (i, l) {
                if (WhoSayPhotoEmbed.jQuery.isFunction(l))
                  l();
              });
              jQueryCallbacks = [];

            }
          };

          var head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
          head.insertBefore(script, head.firstChild);
        }
      }
    }		

	}
})();

WhoSayPhotoEmbed.jQuery = null;
WhoSayPhotoEmbed.loadJQuery();
