//$Header: /home/cvsroot/WoWJob/js/common.js,v 1.24 2008/01/29 15:33:20 gabriel Exp $
addEvent(window,'load',initBrowser,false);


var IMGPATH = '/images';


var isCSS, isW3C, isIE4, isNN4, isIE6CSS;


function bookmarksite(title,url){
if (window.sidebar) // firefox
	window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
} 
else if(document.all)// ie
	window.external.AddFavorite(url, title);
}

function initBrowser() {
  if (document.images) {
    isCSS = (document.body && document.body.style) ? true : false;
    isW3C = (isCSS && document.getElementById) ? true : false;
    isIE4 = (isCSS && document.all) ? true : false;
    isNN4 = (document.layers) ? true : false;
    isIE6CSS = (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? true : false;
  }
}

function IDtoObject(obj) {
  var theObj;
  if (typeof obj == "string") {
    if (isW3C) { theObj = document.getElementById(obj); } 
    else if (isIE4) { theObj = document.all(obj); } 
    else if (isNN4) { theObj = seekLayer(document, obj); }
    else theObj = document.getElementById(obj);
  } else { theObj = obj; }
  return theObj;
}

//needs testing
function frameIDtoObject(frame,obj) {
  var theObj;
  if (typeof obj == "string") {
    if (isW3C) { theObj = frame.document.getElementById(obj); }
    else if (isIE4) { theObj = frame.document.all(obj); }
    else if (isNN4) { theObj = seekLayer(frame.document, obj); }
    else theObj = frame.document.getElementById(obj);
  } else { theObj = obj; }
  return theObj;
}

function setFocus(input) {
  try {
    input.focus();
  } catch(e) {
    //do nothing
  }
}

function setHover(div) {
  var links = div.getElementsByTagName('a');
  for (var i=0; i<links.length; i++) {
    var link = links[i];

    var img = link.getElementsByTagName('img');
    if (!img) continue;

    link.img = img[0];

    link.img.oversrc = link.img.getAttribute('oversrc');
    link.img.outsrc  = link.img.src;

    if (link.img.oversrc) {
      link.onmouseover = function(e) { this.img.src = this.img.oversrc; };
      link.onmouseout  = function(e) { this.img.src = this.img.outsrc; };
    }
  }
}




function getWindowRect() { //http://www.quirksmode.org/viewport/compatibility.html
  var x,y;
  if (self.innerHeight) { //all except Explorer
    x = self.innerWidth;
    y = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { //Explorer 6 Strict Mode
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
  } else if (document.body) { //other Explorers
    x = document.body.clientWidth;
    y = document.body.clientHeight;
  }
  return {'width':x,'height':y};
}

function setWindowRect(x,y,dx,dy) { //http://www.quirksmode.org/viewport/compatibility.html
  if (self.innerHeight) { //all except Explorer
    self.innerWidth = x;
    self.innerHeight = y;
  } else if (document.documentElement && document.documentElement.clientHeight) { //Explorer 6 Strict Mode
    self.resizeBy(dx,dy);
  } else if (document.body) { //other Explorers
    self.resizeBy(dx,dy);
  }
}




function getPage() {
  try {
    var page = document.getElementsByTagName('body')[0].id;
  } catch(e) {
    var page = false;
  }
  return page;
}

function getDayTime() {
  var day = new Date();
  return day.getTime();
}

function trim(s) {  
  if (s.replace) {
    s = s.replace( /^\s+/g, "" ).replace( /\s+$/g, "" );
  }
  return s;
}

function cleanWhiteSpace(s) {
  return s ? s.replace(/\s+/g," ").replace(/^\s/g, "" ).replace( /\s$/g, "" ) : "";
}




function capitalizeWords(val) {
  var newVal = '';
  if (!val)
    return newVal;
  val = val.toLowerCase();
  val = val.split(' ');
  for (var c=0; c < val.length; c++) {
    newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + ' ';
  }
  return newVal.substring(0,newVal.length -1);
}

function shEncodeURIComponent(p) {
  var s = (encodeURIComponent) ? encodeURIComponent(p) : escape(p);
  return s.replace(/%20/g,'+');
}

function shDecodeURIComponent(p) {
  p = p.replace(/\+/g,' ');
  var s = (decodeURIComponent) ? decodeURIComponent(p) : unescape(p);
  return s;
}

function encodeAmp(s) {
  if (s.replace) {
    s = s.replace(/&/g,'&amp;');
    s = s.replace(/</g,'&lt;');
    s = s.replace(/>/g,'&gt;');
  }
  return s;
}

function decodeAmp(s) {
  if (s.replace) {
    s = s.replace(/&gt;/g,'>');
    s = s.replace(/&lt;/g,'<');
    s = s.replace(/&amp;/g,'&');
  }
  return s;
}




function makeDesiredStateLink(state) {
  var ns = ''//getNameSpace(); //alert(ns);
  return '/' + ns + 'rpcproxy.php?ds=' + state + '&' ;
}

function makeAuthLink(state) {
  var ns = ''//getNameSpace(); //alert(ns);
  return '/' + ns + 'auth.php?ds=' + state + '&' ;
}

function makeLink(state, url) {
  var ns = ''//getNameSpace(); //alert(ns);
  return '/' + ns + url + '?ds=' + state + '&' ;
}

function getNameSpace() {
  var hasCobrand = document.URL.match(/^\S*?:\/\/\S*?\/(\S*)\/.*$/); //http://www/cobrand/page
  if (hasCobrand) {
    var cobrand = hasCobrand[1];
    if (checkValidCobrand(cobrand)) return cobrand + '/';
  }

  var hasCobParam = document.location.search.match(/(?:&|^)cob=(\S*?)(?:&|$)/); //...&cob=cob&...
  if (hasCobParam) {
    var cobrand = hasCobParam[1];
    if (checkValidCobrand(cobrand)) return cobrand + '/';
  }

  return '';
}

function checkValidCobrand(cobrand) {
  return true;//(cobrand == 'wowjob');
}

function currentQueryParams(ovr) {
  if (!querydata) return null;
  var qd = querydata;

  //override current parameters
  for (var o in ovr) {
    qd[o] = ovr[o];
  }
  qd.hits = '';
  qd.pages = '';

  //build query string
  var query = [];
  for (var q in qd) {
    if (q && qd[q]) query.push(q + '=' + shEncodeURIComponent(qd[q]));
  }
  return query.join('&');
}




function rpcCall(url, cb, async) {
  if (!$w) {
    callToServer(url);
    if (cb) cb(null);
    return true;
  }
  var http = $w.getTransport();
  var cbdone = false;
  http.onreadystatechange = function(){
    if (http.readyState < 4) return;
    if (cbdone) return;
    cbdone = true;
    if (cb) cb(http);
  }
  http.open("GET", url, async);
  http.send(null);
  if (!async && cb && !cbdone) cb(http);
  return true;
}

function rpcCallPOST(url, cb, async, parameters) {
	
  if (!$w) {
    callToServer(url);
    if (cb) cb(null);
    return true;
  }
  var http = $w.getTransport();
  var cbdone = false;
  http.onreadystatechange = function(){
    if (http.readyState < 4) return;
    if (cbdone) return;
    cbdone = true;
    if (cb) cb(http);
  }
  http.open("POST", url, async);
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.setRequestHeader("Content-length", parameters.length);
  http.setRequestHeader("Connection", "close");
  http.send(parameters);

  //http.send(null);
  if (!async && cb && !cbdone) cb(http);
  return true;
}





var RESPERPAGE = {'10':'10 results', '15':'15 results', '25':'25 results', '30':'30 results'};

//----------USERPREFS
//commenting userprefs code
//var USER_PREFS = {
//  rpp: 10,
//  onw: 'n'
//};

//----------SEARCH
var SEARCHPARAMS = ['q','oras', 'oras_txt', 'domeniu_activitate'];
var BROWSEPARAMS = ['op','ip'];
var ADVPARAMS = ['aw','ep','ow','ww','jtl','cn'];
var LOCPARAMS = ['cy','st','z'];

//----------FILTERS
var LOCFILTERS = {
  'cs': [],
  'mi': {'e':'exact', '5':'within 5 miles', '10':'within 10 miles', '15':'within 15 miles', '25':'within 25 miles', '50':'within 50 miles'}
};
var JOBFILTERS = {
  'tip_job_txt': [],
  'nivel_cariera_txt': [],
  'tip_job_txt': [],
  //'tip_job': ['any','Intern', '0-2 years', '2-5 years', '5-7 years', '7-10 years', '10-15 years', '15+ years', 'Open'],
  //'nivel_cariera': ['oricare','Liceu', 'Facultate', 'Entry-level (sub 3 ani)', 'Middle-level (peste 3 ani)', 'Management Superior'],
  'data_introducere': {'1':'Ultimele 24 de ore', '7':'Ultimele 7 zile', '14':'Ultimele 14 zile', '30':'Ultimele 30 zile'},
  'lv': {'Y':'since last visit','1':'since last visit'},
  'hci': {'Y':'has salary info','1':'has salary info'},
  'sp':{'Y':'Cu salariu precizat'},
  'companie_txt': []
};
var COFILTERS = {
  'ncn' : [],
  'ec': ['all','less than 10 employees', '10-100 employees', '100-500 employees', '500-1000 employees', '1000-5000 employees', '5000+ employees'],
  'rev': ['all','less than $5M', '$5M-$10M', '$10M-$50M', '$50M-$100M', '$100M-$500M', '$500M+'],
  'rl': {'dogfriendly':'Dog-Friendly Companies',
	 '25fastgrowingtechcompanies':'Forbes 25 Fastest-Growing Tech Companies', 'Inc. 500':'Inc. 500', 'fastfortune100':'Fortune 100 Fastest-Growing Companies',
         'forbes400big':'Forbes 400 Best Big Companies', 'fortune100best':'Fortune Best Companies to Work For', 'fortune500companies':'Fortune 500',
         'minority50list':'Fortune Best for Minorities', 'workingmother100':'Working Mother 100 Best', '200smallcompanies':'Forbes 200 Best Small Companies',
	'ecofriendly':'Care2 Eco-Friendly Companies',
	'sociallyresponsible':'Care2 Socially Responsible Companies',
	'nonprofit':'Non-Profit Companies',
	 'glbt':'GLBT-Friendly Companies',
	 'agefriendly':'Age 50+ Friendly Companies'}
};

var queryDetails = new function() {
  this.params = null;

  this.kw = null;
  this.loc = null;
  // city ID
  this.loc_id = null;
  this.fl = null;

  function parseq(query) {
    query = query.split('&');
    var q = [];
    for (i in query) {
      var p = query[i].split('=');
      if (p[1])	q[p[0]] = shDecodeURIComponent(p[1]);
    }
    return q;
  }

  function parsekw(q) {
    var s = [];

    if (q.q) s.push(q.q);

    for (var p in BROWSEPARAMS) {
      var b = q[BROWSEPARAMS[p]];
      if (b) {
	b = b.replace(/(^\||\|$)/g,'');
	b = b.replace(/\|/,' - ');
	s.push(b);
      }
    }

    for (var p in ADVPARAMS) {
      if (q[ADVPARAMS[p]]) s.push(q[ADVPARAMS[p]]);
    }

    return s.join(' ');
  }

  function parseloc(q) {
    if (q.oras_txt) return q.oras_txt;

    var s = ''; //oras, st zip
    if (q.cy) s = q.cy;
    if (q.st) {
      if (s) s += ', ';
      s += q.st;
    }
    if (q.z) {
      if (s) s += ' ';
      s += q.z;
    }
    return s;
  }

  function parselocid(q) {
    if (q.oras) return q.oras;
  }
  
  function parsedom(q) {
    if (q.domeniu_activitate_txt) return q.domeniu_activitate_txt;
  }
  
  function parsedomid(q) {
    if (q.domeniu_activate) return q.domeniu_activitate;
  }
  
  function parsefl(q) {
    var s = [];

    for (var f in LOCFILTERS) {
      if (q[f]) {
        if (LOCFILTERS[f][q[f]]) s.push(LOCFILTERS[f][q[f]]);
        else s.push(q[f]);
      }
    }
    for (var f in JOBFILTERS) { 
      if (q[f]) {
	if (JOBFILTERS[f][q[f]]) s.push(JOBFILTERS[f][q[f]]);
	else s.push(q[f]);
      }
    }
    for (var f in COFILTERS) {
      if (q[f]) {
	if (COFILTERS[f][q[f]]) s.push(COFILTERS[f][q[f]]);  
	else s.push(q[f]);
      }
    }
    return s; //array
  }

  //parse query into parameters
  this.parse = function(query, update) {
    this.params = parseq(query);
	if(!querydata) return;
	if(!update) return;
	for(q in querydata)
		if(this.params[q])
	 		querydata[q]=this.params[q];
	
  };

  //set query parameters
  this.set = function(query) {
    this.params = query;
  };

  //get keywords, location, filteres
  this.get = function(kw,loc,fl) {
    this.kw  = parsekw(this.params);
    this.loc = parseloc(this.params);
    this.loc_id = parselocid(this.params);
    this.dom = parsedom(this.params);
    this.dom_id = parsedomid(this.params);
    this.fl  = parsefl(this.params);
  };
};

function hasSearch(qd) {
  var params = [].concat(SEARCHPARAMS, BROWSEPARAMS, ADVPARAMS, LOCPARAMS);
  for (var i in params) {
    if (qd[params[i]]) return true;
  }
  return false;
}


//geocoder
function geocoder(loc,cb,async) {
  var callback = function(http) {
    var s = http.responseText;
    if (!s) return cb(-1);

    eval('var resp = ' + s);
    var ok = (!resp || (!resp.statecodes && !resp.state));
    cb(ok ? false : resp);
  };

  var url = '/geocoder?location=' + loc + '&taracode=US&df=JSON';
  rpcCall(url,callback,async);
}


//add multiple events safely cross browser
function addEvent(obj,evt,fnc,useCapture) {
  if (!useCapture) useCapture = false;
  if (obj.addEventListener) {
    obj.addEventListener(evt,fnc,useCapture);
    return true;
  } else if (obj.attachEvent) {
    return obj.attachEvent("on"+evt,fnc);
  } else {
    attchEvent(obj,evt,fnc);
    obj['on'+evt]=function(){ fireEvent(obj,evt) };
  }
} 

//the following are for browsers like NS4 or IE5Mac which dont support either attachEvent or addEventListener
function attchEvent(obj,evt,fnc){
  if (!obj.myEvents) obj.myEvents={};
  if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
  var evts = obj.myEvents[evt];
  evts[evts.length]=fnc;
}
function fireEvent(obj,evt){
  if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
  var evts = obj.myEvents[evt];
  for (var i=0,len=evts.length;i<len;i++) evts[i]();
}




//hb nov16
//return array of element obj refs that match attribute name
function getElemsByAttribute(attribute,elementType,parentObjRef){
   var retVal = {};
   var y = parentObjRef.getElementsByTagName(elementType);
   for(var i=0;i<y.length;i++){
      if(y[i].getAttribute(attribute)){
         retVal[y[i].id] = y[i];
      }
   }
   return retVal;
}

//return array of element obj refs that match attribute name
function getElemsByAttributeValue(attribute,value,elementType,parentObjRef){
  var retVal = {};
  var y = parentObjRef.getElementsByTagName(elementType);
  for(var i=0;i<y.length;i++){
    if(y[i].getAttribute(attribute) == value){
      retVal[y[i].id] = y[i];
    }
  }
  return retVal;
}

