if (!window.console) {console = {log:function(str){1;}};}
Function.prototype.bind = function() {
  var __method = this, args = Array.prototype.slice.call(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat(Array.prototype.slice.call(arguments)));
  };
};

var Coolchaser = {
  root_url: "http://www.coolchaser.com",
  btb_div_id: "_coolchaser_btb",
  ie6_status_html: '<div id="overlay" style="display: block; position: absolute; top:-225px; left: 0pt; z-index: 1000012 !important;; width: 100%; height: 3485px; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'http://www.coolchaser.com/images/overlay.png\', sizingMethod=\'scale\');"></div> <div class="lb" style="z-index:1000013 !important; position:absolute; top:-225px; left:0; width:100%; height:3000px;"> <div class="lb_inner" style="position:absolute; margin-top:370px; text-align:center;  border:2px solid #333; background:#fff;   padding:10px 10px 10px 10px;  width:400px;   margin-left:-200px; height:150px; top:expression(eval(document.compatMode && document.compatMode==\'CSS1Compat\') ? documentElement.scrollTop+((documentElement.clientHeight-this.clientHeight)/2 - 155) : document.body.scrollTop +((document.body.clientHeight-this.clientHeight)/2 -155)); "> <h1 style="background:#000; color:#FFFFFF; font-size:14px; margin:-9px -9px 10px; padding:8px 8px 8px 0px; letter-spacing:1px;">Automatic Insert</h1> <p class="loader" id="auto_insert_loader" style="margin:20px 0 0 0; line-height:1.5em; margin-bottom:5px; padding:0 5px 10px 10px;"><img src="http://www.coolchaser.com/images/ajax-loader-big.gif" /></p> <p class="status" style="color:#000; font-size:14px; line-height:1.5em; margin-bottom:5px; padding:0 0 10px 0px; font-family: Lucida Grande, Arial, Verdana, sans-serif;"><span id="auto_insert_status">Please wait, auto inserting now...</span></p> <p class="status" style="color:#000; font-size:14px; line-height:1.5em; margin-bottom:5px; padding:0 0 10px 0px; font-family: Lucida Grande, Arial, Verdana, sans-serif;"><span id="auto_insert_success" style="xdisplay:none"><img src="http://www.coolchaser.com/images/tick.gif" style="border:0; vertical-align:middle; margin-right:3px;" /> Congrats! Your layout has been updated successfully!</span></p> </div> </div>',
  status_html: '<div id="overlay" style="display: block; position: absolute; top:-225px; left: 0pt; z-index: 1000012 !important;; width: 100%; height: 3485px; background-image: url(http://www.coolchaser.com/images/overlay.png);"></div> <div class="lb" style="z-index:1000013 !important; position:absolute; top:-225px; left:0; width:100%; height:100%;"> <div class="lb_inner" style="position:fixed; top:50%; left:48%; text-align:center; border:2px solid #333; background:#fff; padding:10px 10px 10px 10px; margin-top:-70px; width:400px; margin-left:-200px; height:150px; "> <h1 style="background:#000; color:#FFFFFF; font-size:14px; margin:-9px -9px 10px; padding:8px 8px 8px 0px; letter-spacing:1px;">Automatic Insert</h1> <p class="loader" id="auto_insert_loader" style="margin:20px 0 0 0; line-height:1.5em; margin-bottom:5px; padding:0 5px 10px 10px;"><img src="http://www.coolchaser.com/images/ajax-loader-big.gif" /></p> <p class="status" style="color:#000; font-size:14px; line-height:1.5em; margin-bottom:5px; padding:0 0 10px 0px; font-family: Lucida Grande, Arial, Verdana, sans-serif;"><span id="_coolchaser_status">Please wait, auto inserting now...</span></p> <p class="status" style="color:#000; font-size:14px; line-height:1.5em; margin-bottom:5px; padding:0 0 10px 0px; font-family: Lucida Grande, Arial, Verdana, sans-serif;"></div> </div>',
  login_html: '<style> #content { position:relative; } </style><div id="_cc" style=" width:385px; height:196px; position:absolute; top:-20px; right:290px; z-index:1000000; "><img src="http://i150.photobucket.com/albums/s93/quhby/arrow_animated3.gif"><p style="font-family:verdana; font-size:11px;position:absolute;right:120px;text-align:right;top:165px; width:180px;"><img src="http://i150.photobucket.com/albums/s93/quhby/cancel.gif" style="vertical-align:middle" /> <a href="javascript:Coolchaser.cancelAutoInsert()" style="color:#fff; text-decoration:underline">Cancel Auto Insert</a></p></div>',
  getMainWindow: function() {
    return window;
  },
  docComplete: function(tool, doc) {
    this.doc = doc;
    this.win = this.getMainWindow();
    this.tool = tool;
    if (!this.checkUserHome()) {
      this.nextStep();
    }
  },
  atUrl: function(url) {
    return window.location.href == url;
  },
  matchUrl: function(urlFragment) {
    return this.doc.URL.indexOf(urlFragment) >= 0;
  },
  insertHomePageLink: function() {
    console.log('home page link');
    var pickUrlDiv = document.getElementById('pickUrl') || getFirstElementByClass('myurl', 'div');
    if (pickUrlDiv) {
      pickUrlDiv.innerHTML += '<span>[<a href="http://www.coolchaser.com/layout/create" target="_blank">Edit Profile with CoolChaser</a>] <a href="http://www.coolchaser.com/message/help#toolbar_faq" target="_blank" /><img src="http://i150.photobucket.com/albums/s93/quhby/icon_q.gif" style="vertical-align:middle;"></a></span>';
    }
  },
  insertNavBarLink: function() {
      var profileNav = this.doc.getElementById('nav1000010');
      if (profileNav) {
        var profSubMenu = profileNav.children[1];
        var ccElt = this.doc.createElement('li');
        ccElt.innerHTML = '<a href="http://www.coolchaser.com/layout/create" target="_blank" style="z-index:100000"><img src="http://i150.photobucket.com/albums/s93/quhby/favicon_s_blue.gif" style="vertical-align:middle"> Edit Layout&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>';
        //profSubMenu.insertBefore(ccElt, profSubMenu.children[2]);
        profSubMenu.appendChild(ccElt);
      }
  },
  insertEditorLink: function() {
    var headerDiv = document.getElementById('ecpHeader');
    var afterAnchor = document.getElementById('ecpExitBtn');
    if (headerDiv && afterAnchor) {
      var ccAnchor = this.doc.createElement('a');
      ccAnchor.href = 'http://www.coolchaser.com/layout/create';
      ccAnchor.target = '_blank';
      ccAnchor.className = 'sliderBtn silver';
      ccAnchor.innerHTML = '<span><span>Edit with CoolChaser</span></span>';
      headerDiv.insertBefore(ccAnchor, afterAnchor);
    }
  },
  doLinkInsertions: function() {
    this.doc = document;
    try {
      if (this.matchUrl("fuseaction=user")) {
        this.insertHomePageLink();
      }
      else if (this.matchUrl("fuseaction=pageeditor.profile")) {
        this.insertEditorLink();
      }
      if (this.matchUrl("myspace.com")) {
        this.insertNavBarLink();
      }
    }
    catch(e) {}
  },
  cancelAutoInsert: function() {
    this.store('next_handler','');
    document.getElementById('_cc').style.display = 'none';
  },
  checkUserHome: function() {
    if (this.atUrl(this.root_url + '/user/home') && this.win.hasFreeCause) {
      this.win.hasFreeCause();
      return true;
    }
    return false;
  },
  createStatusDiv: function() {
    var div = this.doc.createElement('div');
    div.id = this.btb_div_id;
    div.style.display = 'none';
    div.innerHTML = (navigator.userAgent.indexOf('MSIE 6.') < 0) ? this.status_html : this.ie6_status_html;
    this.statusDiv = div;
    this.doc.body.appendChild(div);
  },
  isNewPage: function() {
    var doc = this.doc;
    if (!doc.body || doc.getElementById(this.btb_div_id)) {
      return false;
    }
    else {
      this.createStatusDiv();
      return true;
    }
  },
  nextStep: function() {
    var next_handler = 'handle' + this.get('next_handler');
    if (this[next_handler] && this.isNewPage()) {
      this[next_handler]();
    }
  },
  updateStatus: function(status, consoleOnly) {
    console.log(status);
    if (consoleOnly) {return;}
    var statusSpan = document.getElementById('_coolchaser_status');
    if (!statusSpan) {
      this.createStatusDiv();
      statusSpan = document.getElementById('_coolchaser_status');
    }
    if (statusSpan) {
      this.statusDiv.style.display = 'block';
      statusSpan.innerHTML = status;
    }
  },
  store: function(key, value) {
    this.tool.SetVariable(key,value);
    return value;
  },
  get: function(key) {
    return this.tool.GetVariable(key);
  },
  navigateTo: function(url, handler, win) {
    this.store('next_handler', handler);
    win = win || this.win;
    win.location.href = url;
  },
  startProfileInsert: function(code1, code2, popupWin, credits) {
    this.store('code1', code1);
    this.store('code2', code2);
    if (credits) {this.store('credits', credits);}
    this.navigateTo("http://profileedit.myspace.com/index.cfm?fuseaction=profile.interests", "EditProfile", popupWin);
  },
  handleMySpaceHome: function() {
    this.updateStatus('Not logged in', true);
    var accountElt = document.getElementById('account');
    if (accountElt) {
      var pos = this.getPosition(accountElt);
      scrollTo(pos[0]-75, pos[1]-350);
    }
    var contentElt = document.getElementById('content');
    if (contentElt) {
      contentElt.innerHTML += this.login_html;
    }
  },
  handleEditProfile: function() {
    if (this.atUrl('http://www.myspace.com/')) {
      this.handleMySpaceHome();
    }
    else {
      var doc = this.doc;
      try {
        var navElt = doc.getElementById('nav1000010');
        var viewProfileUrl =  navElt.href || navElt.firstChild.href; // regular profile is latter case
        this.store('viewProfileUrl', viewProfileUrl);
      }
      catch(e) {this.updateStatus('could not retrieve view profile url', true);}
      if (this.matchUrl("fuseaction=profile.interests")) {
        var contentEditorElt = doc.getElementById('contentEditorMenu');
        if (contentEditorElt) {
          this.updateStatus('Detected Profile 2.0 Layout!');
          this.navigateTo("http://profileedit.myspace.com/index.cfm?fuseaction=pageeditor.profile", 
            'CustomizeProfile2');
        }
        else {
          this.updateStatus('Detected Profile 1.0 Layout!');
          var code1 = this.get('code1');
          var aboutMeField =
            doc.getElementById('ctl00_ctl00_ctl00_cpMain_cpMain_ProfileEditContent_editInterests_AboutMeTextBox');
          aboutMeField.value = this.removeOldCode(aboutMeField.value) + '\n' + code1;
          this.store('next_handler', 'AfterEditProfile');
          doc.getElementById('ctl00_ctl00_ctl00_cpMain_cpMain_ProfileEditContent_editInterests_SaveTop').click();
        }
      }
      else {
        if (this.matchUrl("fuseaction=bandprofile")) {
          this.updateStatus('Detected Band Layout!');
          this.navigateTo('http://editprofile.myspace.com/index.cfm?fuseaction=profile.safemode','BandProfile');
        }
        else if (this.matchUrl("fuseaction=comedian") || this.matchUrl("fuseaction=filmmaker")) {
          this.updateStatus('Detected Comedian or Filmmaker Layout!');
          this.navigateTo('http://editprofile.myspace.com/index.cfm?fuseaction=profile.safemode','OtherProfile');
        }
        else {
          this.updateStatus('hmm, did not navigate to any profile edit page', true);
        }
      }
    }
  },
  handleAfterEditProfile: function() {
    var captchaMsgElt = this.doc.getElementById('captchaMsg');
    if (captchaMsgElt) {
      this.updateStatus('Please submit captcha below...', true);
    }
    else {
      var profileUpdatedElt = this.doc.getElementById('ctl00_ctl00_ctl00_cpMain_cpMain_ProfileEditContent_editInterests_output');
      if (profileUpdatedElt && profileUpdatedElt.innerHTML.length > 0) {
        this.handleAfterInsertion();
      }
    }
  },
  handleSaveCredits: function() {
    var doc = this.doc;
    var generalField = doc.getElementById('ctl00_ctl00_ctl00_cpMain_cpMain_ProfileEditContent_editInterests_GeneralText');
    generalField.value = this.removeOldCode(generalField.value) + this.get('credits');
    this.store('next_handler', 'AfterSaveCredits');
    doc.getElementById('ctl00_ctl00_ctl00_cpMain_cpMain_ProfileEditContent_editInterests_SaveInterests').click();
    this.updateStatus('Detected Profile 2.0 Layout!');
  },
  handleAfterSaveCredits :function() {
    if (this.matchUrl('fuseaction=profile.interests')) {
      this.updateStatus('Detected Profile 2.0 Layout!');
      this.navigateTo("http://profileedit.myspace.com/index.cfm?fuseaction=pageeditor.profile", 
        'CustomizeProfile2');
    }
  },
  handleCustomizeProfile2: function() {
    if (!this.matchUrl('fuseaction=pageeditor.profile')) {
      this.updateStatus('not page editor!', true);
      return;
    }
    try {
      this.savedNoTheme = this.savedCss = false;
      var self = this;
      var code2 = this.get('code2');
      this.win.MySpace.UI.Pages.Data.request("SaveTheme.ashx?pageId=0&themeId=0", null, 
        function() {self.savedNoTheme = true;self.handlePublishProfile2();}, '');
      this.win.MySpace.UI.Pages.Data.request("SaveAdvancedCss.ashx", null, 
       function() {self.savedCss = true;self.handlePublishProfile2();}, 'css=' + escape(code2));
    } catch(e) {console.log(e);}
  },
  handlePublishProfile2: function() {
    this.updateStatus('Updating Profile 2.0 Layout');
    if (this.savedNoTheme && this.savedCss) {
      this.updateStatus('Successfully Updated Profile 2.0 Layout');
      this.win.MySpace.UI.Pages.Data.request("PublishDraft.ashx", null, this.handleAfterInsertion.bind(this),'');
    }
  },
  handleBandProfile: function() {
    if (this.matchUrl('fuseaction=profile.safemode')) {
      this.updateStatus('Insert layout codes...');
      this.store('next_handler', 'Bio');
      this.win.editInterest('bio');
    }
  },
  handleOtherProfile: function() {
    // comedy & filmmaker profiles
    if (this.matchUrl('fuseaction=profile.safemode')) {
      this.updateStatus('Insert layout codes...');
      this.store('next_handler', 'OtherAboutMe');
      this.win.editInterest('aboutme');
    }
  },
  handleOtherAboutMe: function() {
    var interestField = this.doc.forms[1].interest; // or forms[1][1]
    var code1 = this.get('code1');
    interestField.value = this.removeOldCode(interestField.value) + '\n' + code1;
    this.store('next_handler', 'Preview');
    this.doc.forms[1].submit();
  },
  handleBio: function() {
    var interestField = this.doc.forms[1][2];
    var code1 = this.get('code1');
    interestField.value = this.removeOldCode(interestField.value) + '\n' + code1;
    this.store('next_handler', 'Preview');
    this.doc.forms[1][4].click();
  },
  handlePreview: function() {
    // musician, comedy & filmmaker preview
    if (this.matchUrl('fuseaction=profile.previewsafemode')) {
      this.updateStatus('Confirming layout codes...');
      this.store('next_handler','AfterInsertion');
      this.doc.forms[1].submit();
    }
  },
  handleAfterInsertion: function() {
    if (this.matchUrl('fuseaction=profile.safemode') || this.matchUrl('fuseaction=profile.interests') ||
      this.matchUrl('fuseaction=pageeditor.profile')) {
      var statusTxt = 'Layout inserted!';
      var viewProfileUrl = this.get('viewProfileUrl');
      if (viewProfileUrl) {statusTxt += ' Showing your new profile...';}
      this.updateStatus(statusTxt);
      if (viewProfileUrl) {this.navigateTo(viewProfileUrl,''); }
      this.cleanUp();
    }
  },
  cleanUp: function() {
    this.store('next_handler','');
  },
  recursiveRemoveNode: function(node, removalNodes, testFn) {
    if (node) {
      if (testFn(node)) {
        removalNodes.push(node);
      }
      else if (node.nodeType == 1) {
        for(var m = node.firstChild; m != null; m = m.nextSibling) {
          this.recursiveRemoveNode(m, removalNodes, testFn);
        }
      }
    }
  },
  removeOldCode: function(oldCode) {
  
    var div = document.createElement('div');
    div.innerHTML = oldCode;
    var removalNodes = [];
    this.recursiveRemoveNode(div, removalNodes, function(node) {
      return node.nodeType == 1 && 
        node.tagName == "DIV" && (node.className.indexOf('coolchaser') >= 0);
    });
    for (var i=0; i < removalNodes.length; ++i) {
      removalNodes[i].parentNode.removeChild(removalNodes[i]);
    }
    return div.innerHTML;
  },
  getPosition : function(who) { 
      var T= 0,L= 0;
      while(who){
          L+= who.offsetLeft;
          T+= who.offsetTop;
          who= who.offsetParent;
      }
      return [L,T];    
  }
};

function getFirstElementByClass(searchClass,tag,node) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	for (var i=0; i< els.length; ++i) {
	  if (els[i].className == searchClass) {return els[i];}
	}
	return null;
}

function ToolBarInit(tool) {
  Coolchaser.docComplete(tool, document);
}

Coolchaser.doLinkInsertions();
