/* sensitive - see florence */


function toggle(node,style) {

  var state = YAHOO.util.Dom.hasClass(node,style);

  if (state) YAHOO.util.Dom.removeClass(node,style);
  else YAHOO.util.Dom.addClass(node,style);

  return !state;
}

function encode_amp(s) {

  if (s.replace) {
    s = s.replace(/&/g,'&amp;');
    s = s.replace(/</g,'&lt;');
    s = s.replace(/>/g,'&gt;');
  }

  return s;
}

//common.js/ads.js//////////////////////////////////////////////////////////////

//callback invoked by uhi (cpc,cpa)
function sh_ad_request_done(result,type) {
  new SponsoredLinks(result,'sh','c_sponsored_links');
}

//callback invoked by google (afc)
function google_ad_request_done(googleAds) {
  new SponsoredLinks(googleAds,'google','c_google_ads');
}

//callback invoked by google
function google_afs_request_done(googleAds) {
  var tAds = [];
  var bAds = [];
  var rAds = [];
  while (googleAds.length) {
    var ad = googleAds.shift();
    if (tAds.length < sh_afs_top) tAds.push(ad);
    else if (rAds.length < sh_afs_rail) rAds.push(ad);
    else bAds.push(ad);
  }
  if (tAds.length) new SponsoredLinks(tAds,'google','c_google_ads_top',{classname:'google_ads_top',heading_text:sh_afs_heading,highlight:sh_ads_highlight,track_unit:'top'}); //above search results
  if (rAds.length) new SponsoredLinks(rAds,'google','c_google_ads',{classname:'google_ads_rail',heading_text:sh_afs_heading,highlight:sh_ads_highlight,track_unit:'right'}); //right rail
  if (bAds.length) new SponsoredLinks(bAds,'google','c_google_ads_bottom',{classname:'google_ads_bottom',heading_text:sh_afs_heading,highlight:sh_ads_highlight,track_unit:'bottom'}); //below search results
}


function request_cpc_ads() {

  var request = cpc_requrl
              + '/ads/json_feed_fast2.php'
              + '?p_id=' + cpc_p_id
              + '&ad_count=' + cpc_ad_count
              + '&uip=' + cpc_uip
              + '&channel=' + cpc_channel
              + '&limit=' + cpc_limit
              + '&doc_offset=' + cpc_doc_offset
              + '&keyword=' + cpc_keyword
              + '&region=' + cpc_region
              + '&adType=CPC';

  var ads = new AdRequest(request,'cpc',true);

}

function request_cpa_ads() {

  var request = cpa_requrl
              + '/ads/json_feed_fast2.php'
              + '?p_id=' + cpa_p_id
              + '&ad_count=' + cpa_ad_count
              + '&uip=' + cpa_uip
              + '&channel=' + cpa_channel
              + '&limit=' + cpa_limit
              + '&doc_offset=' + cpa_doc_offset
              + '&keyword=' + cpa_keyword
              + '&region=' + cpa_region
              + '&adType=CPA';

  var ads = new AdRequest(request,'cpa',true);

}

function jsonStrFromAdserver(s,ad_type) {
  var result = s ? eval(s) : null;
  sh_ad_request_done(result,ad_type);
}

function AdRequest(url,type,nocache) {

  this.url     = url;
  this.type    = type;
  this.nocache = nocache ? '&nocache=' + (new Date()).getTime() : '';

  this.script  = null;

  this.create_script();
  this.add_script();

}

AdRequest.prototype.create_script = function() {

  var script = document.createElement('SCRIPT');

  script.setAttribute('type','text/javascript');
  script.setAttribute('src',this.url + this.nocache);

  this.script = script;

}

AdRequest.prototype.add_script = function() {

  var head = document.getElementsByTagName('HEAD');

  if (head.length && this.script) head[0].appendChild(this.script);

}

AdRequest.prototype.remove_script = function() {

  var head = document.getElementsByTagName('HEAD');

  if (head.length && this.script) head.removeChild(this.script);

}

/*
 * result     = ad result object
 * provider   = provider
 * node       = ad unit node id
 * properties = ad properties
 *   process_ads:  callback to process ad unit
 *   classname:    ad unit node class
 *   heading_text: heading text
 *   heading_url:  heading url
 *   new_window:   open new window? (default false)
 *   highlight:    highlight ads? (default false)
 *   track_click:  analytics clickhandler
 *   track_unit:   analytics unit id  
 */
function SponsoredLinks(result,provider,node,properties) {

  this.result      = result;
  this.provider    = provider;
  this.node        = document.getElementById(node);
  this.properties  = properties ? properties : {};
  this.ads         = []; //{n,heading,description,source,url}

  if (!this.result || !this.node) return;

  //set default properties for provider
  this.set_provider_properties();

  //process ads using callback
  eval('this.ads = this.'+this.properties.process_ads+'()'); //TODO

  //highlight ads
  if (this.properties.highlight) {
    this.ads = this.highlight_ads();
  }    

  if (this.ads.length) {

    //render node
    this.render_node();

    //render heading
    this.render_heading();

    //render ads
    this.render_ads();

  } else {

    //destroy ad node
    var parent = this.node.parentNode;
    parent.removeChild(this.node);
    this.node = null;

  }

}

SponsoredLinks.prototype.set_provider_properties = function() {

  var default_properties = {};

  if (this.provider == 'google') {
    default_properties = {
      process_ads:'process_google_ads',
      heading_text:'Ads by Google',
      heading_url:'http://services.google.com/feedback/online_hws_feedback',
      new_window:false,
      highlight:false,
      track_click:'sh_view_afs',
      track_unit:'right'
    };
  } else if (this.provider == 'sh') {
    default_properties = {
      process_ads:'process_sh_ads',
      heading_text:'Sponsored Links',
      heading_url:'http://www.simplyhired.lan/a/advertiser-solutions/sponsored-links',
      new_window:true,
      highlight:true
    };
  }
   
  for (var prop in default_properties) {
    if (this.properties[prop] == undefined) this.properties[prop] = default_properties[prop];
  }

}

SponsoredLinks.prototype.process_sh_ads = function() {

  var processed_ads = [];

  var raw_ads = this.result.listing ? this.result.listing : [];

  for (var i=0, n=raw_ads.length; i<n; i++) {

    var raw_ad = raw_ads[i]; //{heading,uri,url,description}

    var url         = raw_ad.uri;
    var heading     = raw_ad.heading;
    var description = raw_ad.description;
    var source      = raw_ad.url;

    processed_ads.push({heading:heading,description:description,source:source,url:url});

  }

  return processed_ads;
}

SponsoredLinks.prototype.process_google_ads = function() {

  var processed_ads = [];

  for (var i=0, n=this.result.length; i<n; i++) {

    var raw_ad = this.result[i]; //{type,n,url,visible_url,line1,line2,line3}

    var url         = raw_ad.url;
    var heading     = raw_ad.line1;
    var description = raw_ad.line3 ? raw_ad.line2+' '+raw_ad.line3 : raw_ad.line2;
    var source      = raw_ad.visible_url;

    processed_ads.push({heading:heading,description:description,source:source,url:url});

  }

  return processed_ads;
}

SponsoredLinks.prototype.highlight_ads = function() {

  var highlighter     = new Highlight();    
  var keywords        = highlighter.parse_keywords(highlighter.get_search_string());

  var highlighted_ads = [];

  for (var i=0, n=this.ads.length; i<n; i++) {

    var ad = this.ads[i];

    ad.heading     = highlighter.highlight_keywords(ad.heading,keywords);
    ad.description = highlighter.highlight_keywords(ad.description,keywords);
    ad.source      = highlighter.highlight_keywords(ad.source,keywords);

    highlighted_ads.push(ad);

  }

  return highlighted_ads;
}

SponsoredLinks.prototype.render_node = function() {

  //set classname
  if (this.properties.classname) {
    this.node.className += ' ' + this.properties.classname;
  }

}

SponsoredLinks.prototype.render_heading = function() {

  //already has heading, nothing to do
  if (this.node.getElementsByTagName('H4').length) return;

  //set heading text and url
  if (this.properties.heading_text) {
    var h4 = document.createElement('H4');
    h4.innerHTML = this.properties.heading_url ? '<a href="'+this.properties.heading_url+'">'+this.properties.heading_text+'</a>' : this.properties.heading_text;
    this.node.appendChild(h4);
  }

}

SponsoredLinks.prototype.render_ads = function() {

  var ul = document.createElement('UL');
  ul.className = '_'+this.ads.length;
  this.node.appendChild(ul);

  for (var i=0, n=this.ads.length; i<n; i++) {

    var ad = this.ads[i];

    var li = document.createElement('LI');

    var href   = ' href="'+ad.url+'"';
    var target = this.properties.new_window ? ' target="_blank"' : '';
    //var mouse  = ' onmouseover="window.status=\''+ad.source+'\';return true;" onmouseout="window.status=\'\';"';
    var mouse = ''; //bug 18853 - window.status typically disabled anyways
    var track  = this.properties.track_click ? ' onmousedown="'+this.properties.track_click+'('+i+',\''+this.properties.track_unit+'\')"' : '';

    li.innerHTML = '';
    li.innerHTML += '<h5 class="title"><a' + href + target + mouse + track + '>' + ad.heading + '</a></h5>';
    li.innerHTML += '<p class="text">' + ad.description + '</p>';
    li.innerHTML += '<p class="site"><a' + href + target + mouse + track + '>'  + ad.source + '</a></p>';

    ul.appendChild(li);
  }

}

function Highlight(){
  
}

Highlight.prototype.get_search_string = function() {
  var search_string = '';
  var search_keywords = YAHOO.util.Dom.get('f_keywords');
  var search_location = YAHOO.util.Dom.get('f_location');
  if(search_keywords){
    search_string += search_keywords.value;
  }
  if(search_location){
    search_string += ' ' + search_location.value;
  }
  return search_string;
}


Highlight.prototype.highlight_keywords = function(content, keywords_array, class_highlight) {
  for(var i in keywords_array){
   var regex = new RegExp("(\\b"+keywords_array[i]+"\\b)", "gi");    
   content = content.replace(regex,'<strong'+(class_highlight?' class="' + class_highlight + '"':'') + '>$1</strong>');
  }
  return content;

}

Highlight.prototype.clean_keywords = function(string){
  string = string.replace(/\s+/g,' '); //trim
  string = string.replace(/^\s+|\s+$/g,''); //trim
  string = string.replace(/(^|\W)\w+\s*:\s*\(?(.+?)\)?/, '$2'); //remove filter
  string = string.replace(/(\^|\$|\*|\+|\?|\=|\!|\:|\||\\|\/|\(|\)|\[|\]|\{|\})/g,'\\$1'); //bug 17476
  return string;
}

Highlight.prototype.parse_keywords = function(string){
  var parsed_keywords = new Array();
  string = this.clean_keywords(string);
  var parser = new Parser();
  parser.init(string); 
  while(parser.has_token()){
    var token = parser.next_token();
    if(token.length > 0){
      parsed_keywords.push(token);    
    }
  }      
  return parsed_keywords;
}

function Parser(){
  var raw_string;
  //TODO: implement a better parser? Try the maximum munch rule with non-deterministic state?
}

Parser.prototype.init = function(text){
  this.raw_string = text;  
}

Parser.prototype.next_token = function(){
  var index = this.raw_string.indexOf('"');  
  var token;
  if(index == 0){      
    index = this.raw_string.indexOf('"', 1) + 1;      
  }
  else{
    index = this.raw_string.indexOf(' ');  
  }  
  if(index > -1){
    token = this.raw_string.substr(0,index);                
  }
  else{
    token = this.raw_string;
    this.raw_string = '';    
  }
    
  this.raw_string = this.raw_string.substr(index + 1);
  if(/^AND$|^OR$/.exec(token)){
    token = this.next_token();      
  }
  else if(/\bNOT\b/.exec(token)){
    this.next_token();
    token = ''; //ignore token
  }
  else if(/^".+?"$/.exec(token)){
    token = token.replace(/^"(.+?)"$/,'$1');      
  }
  else if(/^\W+$/.exec(token)){      
    token = ''; //ignore token      
  }
  else if(/^\W*.+?\W*$/.exec(token)){   //garbage in the end
    token = token.replace(/^\W*(.+?)\W*$/, '$1');
  }
  return token;
  
}

Parser.prototype.has_token = function(){
  return this.raw_string.length > 0;
}

//common.js/validator.js////////////////////////////////////////////////////////

function ValidatorClass() {

  this.email_max    = 256;
  this.email_regex  = /^[a-z0-9\-\_\+]+(\.[a-z0-9\-\_\+]+)*\@(([a-z0-9\-\_\+]+(\.[a-z0-9\-\_\+]+)*){2,}\.[a-z]{2,}|([0-9]+\.){3}[0-9]+)$/i;

  this.trim = function(s) {
    return s.replace ? s.replace(/^\s+/g,'').replace(/\s+$/g,'') : s;
  }

}

ValidatorClass.prototype.validate_email = function(email) {

  if (email == '')
    return 'blank-email';
  else if (email.length > this.email_max)
    return 'long-email';
  else if (email.search(this.email_regex) == -1)
    return 'invalid-email';

  return false;
}

//common.js/cookie.js///////////////////////////////////////////////////////////

function WebAppCookie(app,exp) {

  this.app = app;
  this.exp = exp;

  this.escape = true;

  this.path   = '/';
  this.domain = '';

}

WebAppCookie.prototype.get_cookie = function(key,sep) {

  var cookies = document.cookie.split(/;\s*/);

  for (var i=0, n=cookies.length; i<n; i++) {
    var cookie = cookies[i].split('=');
    if (cookie[0] == this.app+'_'+key) {
      var value = cookie[1];
      if (this.escape) value = unescape(value);
      return value;
    }
  }

  return null;
}

WebAppCookie.prototype.set_cookie = function(key,value,expires) {

  if (this.escape) value = escape(value);

  var cookie = [];
  cookie.push(this.app+'_'+key + '=' + value);
  cookie.push('expires=' + expires);
  if (this.path) cookie.push('path=' + this.path);
  if (this.domain) cookie.push('domain=' + this.domain);

  document.cookie = cookie.join('; ');
}

WebAppCookie.prototype.clear_cookie = function(key) {

  var cookie = [];
  cookie.push(this.app+'_'+key + '=');
  cookie.push('expires=Thu, 01-Jan-70 00:00:01 GMT');
  cookie.push('path=' + this.path);
  cookie.push('domain=' + this.domain);

  document.cookie = cookie.join('; ');
}

WebAppCookie.prototype.get_expiration_days = function() {

  var d = new Date();

  d.setDate(d.getDate() + this.exp);

  return d.toGMTString();
}
