var JobletWidgetAPI = (function () {
  if (!(document.createElement && document.getElementById && document.createTextNode && typeof JobletWidget != 'undefined' )) return false;

  JobletWidget.size.width  = Math.max(JobletWidget.size.width, 150);
  JobletWidget.size.height = Math.max(JobletWidget.size.height,140);
  JobletWidget.type        = JobletWidget.type || 'flashWidget';
  for (var i in JobletWidget.color) {
    JobletWidget.color[i] = JobletWidget.color[i].replace(/^(#)?(\w)(\w)(\w)$/,"$1$2$2$3$3$4$4");
  }

  var isIE = !+"\v1";
  var currentUrlHash = "";

  function checkTopHash() {
    if (currentUrlHash != "" && currentUrlHash != location.hash) {
      console.log(currentUrlHash);
      console.log(location.hash);
      location.reload();
    }
  }

  var crossDomainFunctions = {
    setTopPageHash: function(hash) {
      hash = hash.replace(/^#?/,'#')
      if (hash == currentUrlHash) return;
      location.hash = currentUrlHash = hash;
      window.scrollTo(0,0);
    },

    setWidgetHeight: function(height) {
      height    = parseInt(height);
      var name  = arguments[arguments.length - 1];
      var frame = document.getElementById(name);
      // set iframe's height
      if (height == frame.getAttribute('height')) return;
      frame.setAttribute('height',height);

      // remove ajax loading image
      var elem = document.getElementById(name + '_loading');
      if (elem) { elem.style.display = 'none'; }
    }
  }

  // #setWidgetHeight:::1514-----setTopPageHash:::/jobs?page=7
  // turn has in url to invoke function behavior.
  function invokeCrossDomainFunction(name) {
    var frame = document.getElementById(name);
    if (frame && 
      window[name] && 
      window[name]['widgetSite'] && 
      window[name]['widgetSite'].location.hash) {
      var fun_string = window[name]['widgetSite'].location.hash.replace(/^#/,'');
      var fun_arrays = fun_string.split('-----');
      for (var i = 0; i < fun_arrays.length; i++) {
        var fun_and_args = fun_arrays[i].split(':::');
        fun_and_args[1]  = fun_and_args[1].split(','); // arguments
        fun_and_args[1].push(name);
        crossDomainFunctions[fun_and_args[0]].apply(this,fun_and_args[1]);
      }
    }
  }

  function delayJob(fun,args) {
    if (!isIE || document.readyState == "complete") {
      // if args is false,means this is invoked from setTimeout.
      if (!(fun instanceof Function)) {
        args = delayJob[fun][1];
        fun  = delayJob[fun][0];
      }

      fun.apply('',args);
    } else {
      if (fun instanceof Function) {
        var uniqueId = Math.random().toString();
        delayJob[uniqueId] = [fun,args];
      } else {
        var uniqueId = fun;
      }

      setTimeout("JobletWidgetAPI.delayJob('" + uniqueId + "')", 100);
    }
  }

  // Widget Modes
  with (JobletWidget) {
    var Widgets = {
      flashWidget : function () {
        with (color) {
          var lang   = JobletWidget.lang;
          var vars   = 'title_color=' + title + '&frame_color=' + title_bg + '&content_color=' + content + '&content_bg_color=' + content_bg + '&service_url=' + joblet_url + '/blogs/' + id + '/' + lang + '/jobs.xml';
          var widget = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"                          \
                          id="joblet_ads_widget" width="' + size.width + '" height="' + size.height + '"      \
                          codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">    \
                          <param name="movie" value="' + joblet_url + '/flash_widget/joblet_ads_widget.swf" />       \
                          <param name="quality" value="high" />                                               \
                          <param name="bgcolor" value="#ffffff" />                                            \
                          <param name="allowScriptAccess" value="always" />                                   \
                          <param name="flashvars" value="' + vars + '">                                       \
                          <embed src="' + joblet_url + '/flash_widget/joblet_ads_widget.swf" quality="high" bgcolor="#ffffff"      \
                            width="' + size.width + '" height="' + size.height + '" name="joblet_ads_widget" align="middle" \
                            play="true"                                                                       \
                            loop="false"                                                                      \
                            quality="high"                                                                    \
                            flashvars="' + vars + '"                                                          \
                            allowScriptAccess="always"                                                        \
                            type="application/x-shockwave-flash"                                              \
                            pluginspage="http://www.adobe.com/go/getflashplayer"/>                            \
                        </object>';
          var tmp_elem = document.createElement('span');
          tmp_elem.innerHTML = widget;
          return tmp_elem.childNodes[0];
        }
      },
      htmlWidget : function () {
        var htmlWidgetColor = {};
        for (var i in JobletWidget.color) {
          htmlWidgetColor[i] = JobletWidget.color[i].replace(/^(#)/,"");
        }

        with(htmlWidgetColor) {
          var frameUrl  = joblet_url + '/widget?id=' + JobletWidget.id + '&lang=' + lang + '&title=' + title + '&title_bg=' + title_bg + '&content=' + content + '&content_bg=' + content_bg;
          var frame = document.createElement('iframe');
          frame.setAttribute('width' ,size.width);
          frame.setAttribute('height',size.height);
          frame.setAttribute('src',frameUrl);
          frame.style.border = "solid 1px #" + title_bg;
          return frame;
        }
      },
      mySite : function () {
        var lang = JobletWidget.lang;
        var path = document.location.hash.replace(/^#?/,'/blogs/' + id + '/site');
        path = path + (/\?/.test(path) ? '&' : '?') + 'url=' + escape(location.protocol + '//' + location.hostname + (location.port ? (':' + location.port) : '') + '/robots.txt') + '&global_language=' + lang;
        name = 'a' + parseInt(Math.random() * 10000);
        var frameUrl = joblet_url + path;

        var frame = document.createElement('iframe');
        frame.setAttribute('id', name);
        frame.setAttribute('width', size.width || '100%');
        frame.setAttribute('name', name);
        frame.setAttribute('src', frameUrl);
        frame.setAttribute('frameborder','0');
        frame.setAttribute('allowtransparency',true);

        if (size.height) {
          frame.setAttribute('height', size.height);
        } else {
          // BEGIN Ajax Loading, only show it when height is set
          var div = document.createElement('div');
          div.setAttribute('width', size.width);
          div.setAttribute('style', 'text-align : center');
          var img = document.createElement('img');
          img.setAttribute('src',joblet_url + '/stylesheets/images/job_board_loading.gif');
          img.setAttribute('id',name + '_loading');
          div.appendChild(img);
          var elem = document.getElementById('joblet_widget_api');
          elem.parentNode.insertBefore(div,elem);
          // END Ajax Loading

          frame.setAttribute('height', 0);
          frame.setAttribute('scrolling','no');
        }
        window.setInterval("JobletWidgetAPI.invokeCrossDomainFunction('" + name + "')", 100);
        return frame;
      }
    }
  }

  // get joblet url from src attr of script
  var elem       = document.getElementById('joblet_widget_api');
  var joblet_url = elem.getAttribute('src').replace(/((\w+):\/\/[^\/]*)\/.*/,'$1');
  if (!joblet_url.match(/^http/)) joblet_url = location.protocol + '//' + location.host;

  var parent     = elem.parentNode || elem.parentElement;
  function init(parent, elem) {
    // replace script element with iframe
    parent.replaceChild(Widgets[JobletWidget.type].apply(), elem);
  }
  delayJob(init, [parent,elem]);

  // return methods of JobletWidgetAPI
  return {
    delayJob : delayJob,
    checkTopHash: checkTopHash,
    invokeCrossDomainFunction : invokeCrossDomainFunction
  }
})();

window.setInterval("JobletWidgetAPI.checkTopHash()",500);