/* Site wide javascript stuff (think site-wide search, dialog boxes, etc)

  (c) Copyright 2009, Compete Inc. 
*/


function master_load() {
  // selects the content of each input when a user clicks on them
  $j('input').bind('focus', utils.handle_input_focus);

  $j('form#search-form input[name=q]').bind('focus', _handle_q_focus);
  $j('form#search-form input[name=q]').bind('blur', _handle_q_blur);
  $j('form#search-form').submit(_handle_site_search_form_submit);
  myMenu = $j('#site-menu');
}

function generate_search_dropdown(selectedItem) {
  /* Creates the options dropdown on the search section displayed on most
     pages of the site, and binds the functions that trigger when an item is
     selected
     @param {String} selectedItem - "site_profiles", "tag_profiles", or any other option
  */
  // check if the dropdown exists before trying to create it
  if (!$j('#search-options')) { return false; }
  
  // create the dropdowns
  add_group('search-options', 'Profiles', 'profiles', undefined, {"z_index":1500});
  
  add_list_item('search-options',
                'site_profiles',
                'content(?)',
                'Site Profiles<div class="item-description">see data for a site</div>',
                'item-name',
                'profiles');
  add_list_item('search-options', 
                'tag_profiles', 
                'content(?)', 
                'Tag Profiles<div class="item-description">see all sites in a tag</div>',
                'item-name',
                'profiles');

  // select the default item 
  select_item('search-options', selectedItem, 'profiles');
  
  // handle the clicks
  $j(document).bind('item_selected', function(event, dropdown_div_id, item_object) {
    if (dropdown_div_id != 'search-options') { return false; }

    // Handle the event
    var t = $j('form#search-form input[name=t]');
    var q = $j('form#search-form input[name=q]');
    var search_type = item_object.id.split('-').slice(-1);
    t.val(search_type);
    if (q.val() == '' || q.val().slice(0, 4) == 'e.g.') {
      q.val(_get_default_q_value(search_type));
    }

    // cleanup
    if (event) { event.stopPropagation(); }
  })               
}

function _get_default_q_value (search_type) {
  /* returns the default message input#q gets if it's empty, according to the
  given search_type
  */
  d = {'site_profiles': 'e.g. compete.com',
       'tag_profiles': 'e.g. a-common-tag'}
  return d[search_type]
}

function _handle_q_focus () {
  /* runs when input#q (the keyword field) goes on focus
  */
  q = $j('form#search-form input[name=q]')
  // all the example items must begin w/ e.g.
  if (q.attr('value').slice(0, 4) == 'e.g.') {
    q.attr('value', '')
    q.removeClass('virgin')
  }
}

function _handle_q_blur () {
  /* runs when the input#q (the keyword field) goes out of focus
  */
  q = $j('form#search-form input[name=q]')
  if ($j.trim(q.attr('value')) == '') {
    q.addClass('virgin')
    q.attr('value', _get_default_q_value($j('input[name=t]').val()))
  }
}

function _handle_site_search_form_submit() {
  /*
  */
  var q = $j.trim($j('form#search-form input[name=q]').attr('value'))

  // form is empty
  if (q == '' || q.slice(0, 4) == 'e.g.') {
    return false
  }
  // form is good, do your magic
  var form = $j('form#search-form');
  $j.ajax({'url': form.attr('action'),
           'data': form.serialize(),
           'beforeSend': function() {$j('form#search-form input[name=q]').addClass('loading')},
           'success': _search_success_callback,
           'complete': function() {$j('form#search-form input[name=q]').removeClass('loading')}
    })
  return false  
}

function _search_success_callback (json_str) {
  /* Gets a json string as returned by _search, and acts appropriately.
     > If a redirect_key (w/ val != '') comes w/ the json, it redirects to 
       that page 
     > If an error key comes w/ the json, it opens a ui-dialog w/ appropriate
       verbiage
  */
  json = eval("(" + json_str + ")")
  
  if (json.error == true) {
    _show_dialog(json.message, 'error')
  }
  else if (json.warning == true) {
    _show_dialog(json.message, 'warning')
  }
  else {
    window.location = json.redirect;
  }
}

function _show_dialog(contents, dialog_type, dialog_kwargs) {
  /* Given a jquery object to append to the dialog (i.e. ('<div></div>'), 
     it does exactly that (i.e. appends it), then triggers the dialog.
     dialog_type will decide which color is the header (error -> red, 
     warning -> orange)
  */
  var dialog = $j('<div></div>').addClass('dialog-search')
  dialog.append(contents)
  
  var dialog_defaults = { 
    bgiframe:true,
    draggable:false,
    modal:true,
    resizable:false,
    width:450,
    height:230,
    zIndex:'9999',
    open: function() {$j(this).focus().trigger('mousedown');},
    close: function() {$j('form#search-form input[name=q]').select();}
  };
  // update the dialog default w/ dialog_kwargs
  if (dialog_kwargs) {
    $j.each(dialog_kwargs, function(key, value) {
      if (key) {dialog_defaults[key] = value;}
    });
  }
  
  // set and display the dialog box
  dialog.dialog(dialog_defaults);

  if (dialog_type == 'warning') {
    $j('.ui-widget-header').css('background', 'url(/site_media/images/seaeagle/jqueryui_dialogbox_titlebar_warning.png) repeat-x scroll 50% 50%')
  }
  if (dialog_type == 'error') {
    $j('.ui-widget-header').css('background', 'url(/site_media/images/seaeagle/jqueryui_dialogbox_titlebar_error.png) repeat-x scroll 50% 50%')
  }
}


/**
 * Updates the login or logout link with the current page in the URL.
 * This is done to fix the login/logout bug with the m/ prefix.
 * It's tough to do this through code since some are internal redirects while others are legit prefixes (like m/)
 */
function update_login_logout_link()
{
	// only one of these will actually be on the page
	$j("#mycompete_signup_link").attr("href", member_site + "/login/?origin=" + encodeURIComponent(document.location.href));
	$j("#mycompete_signout_link").attr("href", member_site + "/logout/?origin=" + encodeURIComponent(document.location.href));
}



// From here to line 374 - I.E. to the end of menuUnHoverTimeout method is
// For sitewide Pop-up on site links.

//Global variables required for site-wide popup
var myMenu = false;
var siteHovered = false;
var menuHovered = false;
var menuDisplayed = false;
var siteTimeout = null;
var menuTimeout = null;
var siteName = "";
var siteDomain = "";
var blockedFor = "";
var leftVal = 0;
var topVal = 0;
var siteInterval = null;

//Build the sucker
function createPopUpMenu(site,domain){
  
  myMenu.html("");
  var siteMenu = $j("#site-menu").addClass('site-popup-container').hide();
  var menuBorder = $j("<div></div>").addClass('menu-border');
  siteMenu.append(menuBorder);
  if ((site == "No Site -- Error") || (site == "")) {
    site = "No Site Selected";
    var sitePopUp = $j("<ul></ul>").addClass('site-popup');
    var siteTitle = ellipsify(site,20);
    var sitePopUpHeader = $j("<li title=\""+site+"\"></li>").addClass('site-popup-header').append(siteTitle);
    sitePopUp.append(sitePopUpHeader);
    
  } else{
    
    var sitePopUpDivider1 = $j("<HR>").addClass("site-popup-divider");
    var sitePopUpDivider2 = $j("<HR>").addClass("site-popup-divider");
    var sitePopUpDivider3 = $j("<HR>").addClass("site-popup-divider");
    var sitePopUpDivider4 = $j("<HR>").addClass("site-popup-divider");
    var sitePopUpDivider5 = $j("<HR>").addClass("site-popup-divider");
    
    var sitePopUp = $j("<ul></ul>").addClass('site-popup');
    
    var siteTitle = ellipsify(site,20);
    var visitSiteLink = 'http://' + site + '/';
    var visitSiteAnchor = $j("<a></a>").attr("href", visitSiteLink).attr('target', '_blank').html(siteTitle);
    var sitePopUpHeader = $j("<li title=\""+site+"\"></li>").addClass('site-popup-header').append(visitSiteAnchor);
    
    var addToPortfolioLink = member_site + '/addview/?domain1=' + site;
    var addToPortfolio = $j("<li></li>").addClass('add-to-portfolio');
    var addToPortfolioAnchor = $j("<a></a>").attr("href",addToPortfolioLink).html("add to portfolio");
    addToPortfolio.append(addToPortfolioAnchor);
    
    var viewSiteProfileLink = snapshot_site + '/' + site + '/';
    var viewSiteProfile = $j("<li></li>").addClass('view-site-profile');
    var viewSiteProfileAnchor = $j("<a></a>").attr("href",viewSiteProfileLink).html('view Site Profile');
    viewSiteProfile.append(viewSiteProfileAnchor);

    var runKeywordReferralLink = searchtools_site + '/site_referrals/' + site;
    var runKeywordReferral = $j("<li></li>");
    var runKeywordReferralAnchor = $j("<a></a>").attr("href",runKeywordReferralLink).html('run Search Report');
    var noRunKeywordReferralSpan = $j("<span></span>").html('run Search Report');

    if (site == domain) { 
      runKeywordReferral.addClass('run-keyword-referral');
      runKeywordReferral.append(runKeywordReferralAnchor);
    } else {    
      runKeywordReferral.addClass('run-keyword-referral-inactive');
      runKeywordReferral.append(noRunKeywordReferralSpan);
    }

    
    var runReferralLink = reftools_site + '/referrals/' + site + '/';
    var runReferral = $j("<li></li>");
    var runReferralAnchor = $j("<a></a>").attr("href",runReferralLink).html('run Referral Report');
    var noRunReferralSpan = $j("<span></span>").html('run Referral Report');

    if (site == domain) { 
      runReferral.addClass('run-referral')
      runReferral.append(runReferralAnchor);
    } else {    
      runReferral.addClass('run-referral-inactive');
      runReferral.append(noRunReferralSpan);
    }
    
    var runReferralDestinationLink = reftools_site + '/destinations/' + site + '/';
    var runReferralDestination = $j("<li></li>");
    var runReferralDestinationAnchor = $j("<a></a>").attr("href",runReferralDestinationLink).html('run Destination Report');
    var noRunReferralDestinationSpan = $j("<span></span>").html('run Destination Report');
    
    if (site == domain) {
      runReferralDestination.addClass('run-referral-destination');
      runReferralDestination.append(runReferralDestinationAnchor);
    } else {
      runReferralDestination.addClass('run-referral-destination-inactive');
      runReferralDestination.append(noRunReferralDestinationSpan);
    }
    
    sitePopUp.append(sitePopUpHeader);
    sitePopUp.append(viewSiteProfile).append(sitePopUpDivider1);
    sitePopUp.append(addToPortfolio).append(sitePopUpDivider2);
    sitePopUp.append(runKeywordReferral).append(sitePopUpDivider3);
    sitePopUp.append(runReferral).append(sitePopUpDivider4);
    sitePopUp.append(runReferralDestination).append(sitePopUpDivider5); 
  }
  menuBorder.append(sitePopUp);
}



// What do we do when the user hovers on the link that makes this pop?
function siteHover(e)  {
  getSite(this);
  topVal = 0;
  leftVal = 0;
  scrollOffSet = getScrollXY();
  maxWidth = $j(window).width() + scrollOffSet[0];  
  maxHeight = $j(window).height() + scrollOffSet[1];
  topVal = e.pageY - 80 ;
  leftVal = e.pageX + 50;
  
  if (topVal + 218  > maxHeight) { topVal = maxHeight - 208 ;  }
  if (leftVal + 256 > maxWidth) { leftVal = e.pageX - 256 ;  }
  if (topVal < 0) { topVal = 0 ; }
  if (leftVal < 0 ) { leftVal = 0; }
  topVal = topVal + "px";
  leftVal = leftVal + "px";
  
  if ( blockedFor == "" )  {
    blockedFor = siteName;
  }  
  if ((blockedFor == siteName) && (!menuDisplayed)) {
    
    processSiteHover();
    
  } else {
    clearInterval(siteInterval);
    siteInterval = null;
    siteInterval = setInterval(clearBlock,200)
  }
}
function processSiteHover() {
  if (siteTimeout) {
     clearTimeout(siteTimeout);
     siteTimeout = null;
   }
   if (menuTimeout) {
     clearTimeout(menuTimeout);
     menuTimeout = null;
   }
   siteHovered = true;
   if (! menuHovered ) {
     if ( menuDisplayed ) {
       myMenu.hide();
       myMenu.html("");
       menuDisplayed = false;
       menuHovered   = false;
       if (menuTimeout) {
         clearTimeout( menuTimeout );
         menuTimeout = false;
       }
     }
     myMenu.html("");
     createPopUpMenu(siteName,siteDomain);
     myMenu.hover( menuHover, menuUnHover );
     myMenu.css({left:leftVal,top:topVal});
   }
   siteTimeout = setTimeout( displayMenu, 1000 );
}
function clearBlock() {
  blockedFor = siteName;
  clearInterval(siteInterval);
  siteInterval = null;
  processSiteHover();
}
function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop  += obj.offsetTop;
    } while (obj = obj.offsetParent) ;
  }
  return [curleft,curtop];
}
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}
//What do you do when they move off of that hover
function siteUnHover() {
  siteHovered = false;
  clearTimeout(siteTimeout);
  clearInterval(siteInterval);
  siteTimeout = setTimeout( menuUnHoverTimeout, 400);
}

//We gotta display the menu sometime after we build it...
function displayMenu() {
  clearTimeout(siteTimeout);
  if (!menuDisplayed) {
    menuDisplayed=true;
    myMenu.show();
  }
}

//What do we do when the user hovers on the displayed menu?
function menuHover() {
    menuHovered = true;
    clearTimeout(menuTimeout);
    clearTimeout(siteTimeout);
    clearInterval(siteInterval);
    blockedFor = "";
    menuTimeout = false;
    siteTimeout = false;
}

//What do we do when the user moves off of the menu?
function menuUnHover() {
  menuHovered = false;
  clearTimeout(menuTimeout);
  if (!siteHovered) {
    menuTimeout = setTimeout( menuUnHoverTimeout, 200 );
  }
}

//What do we do 200 Milliseconds after the users moves their cursor off of the menu?
function menuUnHoverTimeout() {
  if (!menuHovered) {
    myMenu.hide(); 
    menuDisplayed=false; 
    menuHovered=false;
    myMenu.html("");
  }
}

function getSite(obj) {
  siteName = "";
  siteDomain = "";
  for (attribute in obj.attributes){
    if (obj.attributes[attribute]) {
      if (obj.attributes[attribute].name == "site"){
        siteName = obj.attributes[attribute].value;
      }
      if (obj.attributes[attribute]) {
        if (obj.attributes[attribute].name == "domain") {
          siteDomain = obj.attributes[attribute].value;
        }
      }
    }
  }
  if (siteDomain == "") { siteDomain = siteName;}
}
