/*
 *  This is aggregate file form: functions.js, my_searches.js, utils.js,
 */

window.onload = init;

function init() {
	buttonHovers();
	makeFocus();
	prettyForms();
  blurLinks();
  load_searches();
  DisplayWelcomeMessage(onload_username, onload_cookie);
//  alert('hellooooo');
};

function removeClass(elt, cls) {
  if (elt == null || !elt.className) { return; }
  elt.className = removeToken(elt.className, cls);
};

function removeAllClasses(elt) {
  elt.className = '';
};

function addClass(elt, cls) {
  if (elt == null || cls == null || cls == '') return;
  if (!hasToken(elt.className, cls)) {
    elt.className += ' ' + cls;
  }
};


function getTokenizedRegExp(token, flags) {
  if (!arguments.callee.res) { arguments.callee.res = {}; }
  var res = arguments.callee.res,
      re = res[token + flags];
  if (!re) {
    re = res[token + flags] = new RegExp("(^|\\s)" + token + "(?!-)\\b", flags);
  }
  return re;
};

function hasToken(string, token) {
  return string.search(getTokenizedRegExp(token, "g")) >= 0;
};

function removeToken(string, token) {
  return string.replace(getTokenizedRegExp(token, "g"), ''); //.trim();
};


/* Removes spaces from the beginning and the end ot the text. */
function trim(text){
    // Removes spaces from the beginning of the text.
    var re = /^ /;
    while(re.test(text)){
        text = text.replace(re, "");
    }

    // Removes spaces from the end of the text.
    var re1 = / $/;
    while(re1.test(text)){
        text = text.replace(re1, "");
    }

    return text;
};


/* Returns Ids of elements with a specific className */
function getElementsIdsByClassName(clsName, parentEle, tagName) {
  var found = new Array();
  var re = new RegExp('\\b'+clsName+'\\b', 'i');
  var list = getElementsByTagName(tagName, parentEle);
  for (var i = 0; i < list.length; ++i) {
    if (list[i].className.search(re) != -1) {
      found[found.length] = list[i];
    }
  }
  return found;
}

function getElementsByTagName(tagName, parentEle) {
  var list = null;
  tagName = tagName || '*';
  parentEle = parentEle || document;
  if (document.all) {
    if (tagName == '*') list = parentEle.all;
    else list = parentEle.all.tags(tagName);
  }else if (parentEle.getElementsByTagName) {
      list = parentEle.getElementsByTagName(tagName);
  }

  return list || new Array();
}

/*
 * Get cookie by name
 */
function get_cookie(c_name) {
  var cookie_value = '';
  if (document.cookie.length > 0) {
    // set cookie start
    var cookie_start = document.cookie.indexOf(c_name + '=');
  	if (cookie_start != -1) {
  	  cookie_start = cookie_start + c_name.length + 1;
      // set cookie end
  	  var cookie_end = document.cookie.indexOf(';', cookie_start);
  	  if (cookie_end == -1) {
        cookie_end = document.cookie.length;
      }
      // get cookie value
  	  cookie_value = unescape(document.cookie.substring(cookie_start, cookie_end));
  	}
  }
  return cookie_value;
};

/*
 * Set cookie
 */
function set_cookie(c_name, c_value, c_expire) {
  var cookie_string = c_name + "=" + escape (c_value);
  var date          = new Date();
  var expires       = '';

  if (!c_expire) {
		date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
  }
  else {
    date.setTime(date.getTime() + c_expire);
  }
  expires          = '; expires=' + date.toGMTString();
  cookie_string   += expires + '; path=/';
  document.cookie  = cookie_string;
};

/*
 * Delete cookie by name
 */
 function delete_cookie(c_name) {
  var c_period = (-1 * 24 * 60 * 60 * 1000);
  set_cookie(c_name, '', c_period);
};
var cookie_name = 'search';
var delimiter   = '|!|';

/*
 * Load previous searches
 */
function load_searches() {
  var my_searches = document.getElementById('my_searches');
  if (!my_searches) {
    return false;
  }

  // get old cookie
  var old_cookie = get_cookie(cookie_name);

  if (old_cookie == '') {
    my_searches.innerHTML = '&nbsp;';
	  return false;
  }

  // put cookie links to array
  var links      = old_cookie.split(delimiter);
  var html_links = '' ;

  for (var i = 0; i < links.length; i++) {
    if (links[i] != '') {
      // set delete images
    	var img1 = conf_host + 'images/delete-search_over.gif';
    	var img2 = conf_host + 'images/delete-search.gif';
    	var link_id  = 'indx_' + i;

      // build my search links
    	var link      = "\n" + '<a href="#"><span title="' + my_search + ' ' + links[i] + '" onclick="submit_form(\'' + links[i] + '\');" >' + links[i] + '</span></a>';
    	link          = link + '<img id="indx_' + i + '" src="' + conf_host + 'images/delete-search.gif" onmouseover="document.getElementById(\'' + link_id + '\').src = \'' + img1 + '\';"';
    	link          = link + ' onmouseout="document.getElementById(\'' + link_id + '\').src = \'' + img2 + '\';" onclick="remove_link(\'' + links[i] + '\');" title="' + my_search_remove + ' ' + links[i] +'" />';
    	html_links    = html_links + link;
    }
  }
  my_searches.innerHTML = html_links;
};

/*
 * Remove link from my searches
 */
function remove_link(val) {

  // get cookie
  var old_cookie = get_cookie(cookie_name);

  // For compatibility with old versions - begin
  var start_delim = old_cookie.substr(0, delimiter.length);
  var end_delim   = old_cookie.substr(old_cookie.length - delimiter.length, delimiter.length);

  if (start_delim != delimiter) {
    old_cookie = delimiter + old_cookie;
  }
  if (end_delim != delimiter) {
    old_cookie = old_cookie + delimiter;
  }
  // For compatibility with old versions - end

  // Remove value
  old_cookie = old_cookie.replace(delimiter + val + delimiter, delimiter);

  if (old_cookie != delimiter) {
    set_cookie(cookie_name, old_cookie);
  }
  else {
    delete_cookie(cookie_name);
  }
  load_searches();

  return true;
};

/*
 * Checks if the search field is empty or less than 3 characters.
 */
function go_searches() {

  // set search query
  var text = document.govidForm.query.value;
  if (trim(text).length > 0) {
	  var val    = trim(text);
	  val    = val.replace(/\'/gi, '');
	  val    = val.replace(/\"/gi, '');
	  val    = val.replace(/\|/gi, '');
	  val    = val.replace(/\`/gi, '');
	  val    = val.replace(/\//gi, '');
	  val    = val.replace(/\!/gi, '');

    // get cookie
    var old_cookie = get_cookie(cookie_name);

	  if (old_cookie != '') {
      var exist = old_cookie.indexOf(delimiter + val + delimiter);
      if (exist < 0) {
        old_cookie = old_cookie + val + delimiter;
      }
	  }
	  else {
		  old_cookie = delimiter + val + delimiter;
	  }

    set_cookie(cookie_name, old_cookie);
    load_searches();

		return true;
	}
	else {
    document.govidForm.query.value = '';
    document.govidForm.query.focus();

	  return false;
	}
};
function SubmitSearch(url) {
      var site    = trim(document.govidForm.site.value);
      var v    = trim(document.govidForm.query.value);
	  v    = v.replace(/\'/gi, '');
	  v    = v.replace(/\"/gi, '');
	  v    = v.replace(/\|/gi, '');
	  v    = v.replace(/\`/gi, '');
	  v    = v.replace(/\//gi, '');
      v    = v.replace(/\!/gi, '');
      if (go_searches() == true ) {
        var new_url = url + site + "/" + v + "/";
        window.open(new_url);
		return false;
      }
	  return false;

}

/*
 * Submit form
 */
function submit_form(form_value) {
  var search_form = document.getElementById('govidForm');
	search_form.query.value = form_value;
	search_form.submit();
};


/* get the XMLHttp object */
function GetXmlHttpObject(){
	var objXMLHttp=null;
	if (window.XMLHttpRequest){
		objXMLHttp=new XMLHttpRequest();
	}else if (window.ActiveXObject){
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}else{
	    alert('Your browser does not support Ajax. Please upgrade');
	    return false;
	}
	return objXMLHttp;
};

/* ajax function which gets the rating and broken website report  and sends them to the url. */
 function AjaxPostForm(parameters,url) {
      http_request = false;
	  http_request = GetXmlHttpObject();
      http_request.open('POST', url, true);
	  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.onreadystatechange  = function() { 	  // if xmlhttp shows "loaded"
        if (http_request.readyState==4){
        // if "OK"
            if (http_request.status==200){
				 var text = http_request.responseText;
				 if ( text == "OK" )
				 {

					 return 'aaa';

				 } else if ( text == "ERR"){

				     return 'bbb';

				 }else{

				 var temp = text.indexOf("&");
				 var flag = text.substr(0, 1)
				 var div_name=text.substr(1, temp-1);
     		     var message=text.substr(temp+1);
				 showSimpleDiv(div_name);
				 document.getElementById(div_name).innerHTML = message;
				 //remove the classes for this div
				 removeAllClasses(document.getElementById(div_name));
				 //add the new classes
				 if (flag == 0) {
				   addClass(document.getElementById(div_name), "answerVote clearfix");
				 }
				 else {
				   addClass(document.getElementById(div_name), "answerVoteErr clearfix");
				 }

				 // Hide all other answer divs
				 hideAnswerDivs(div_name);
                 }
            }else{
                  alert("Problem retrieving data:" + http_request.statusText)
            }
        }
      }

	  http_request.send(parameters);
};


/* function counting symbols left in a text field ( used in addwebsite.php ) */
function textCounter(field, countfield, maxlimit) {
  if (field.value.length > maxlimit) // if too long...trim it!
    field.value = field.value.substring(0, maxlimit);
  // otherwise, update 'characters left' counter
  else
    countfield.value = maxlimit - field.value.length;
};



//function called when rating
function vote(website_id, value, username, message) {
  url = global_url + "?website_id=" + website_id + "&div_name=message_div_" + website_id + "&lcode=" + global_lcode;
  div_id = "message_div_" + website_id;
  if (username == "") {
	 document.getElementById(div_id).innerHTML   = message;
	 removeAllClasses(document.getElementById(div_id));
     addClass(document.getElementById(div_id), "answerVoteErr");
	 showSimpleDiv(div_id);
	 // Hide all other answer divs
	 hideAnswerDivs(div_id);
  }
  else{
     parameters = "rating=" + value;
     AjaxPostForm(parameters,url);
  }

};

//function report broken link
function ReportBroken(website_id) {
  url = global_url_report + "?website_id=" + website_id + "&div_name=message_div_" + website_id + "&lcode=" + global_lcode;
  AjaxPostForm("",url);
};

/* SHOW & HIDE DIV */
function showDiv(id) {
    if (document.getElementById) {
        el = document.getElementById(id);
        if (el.style.display == 'none') {
            document.getElementById('option' + id).src = conf_host + 'images/up.gif';
            el.style.display = '';
        } else {
            document.getElementById('option' + id).src = conf_host + 'images/down.gif';
            el.style.display = 'none';
        }
    }
};

/* SHOW DIV */
function showSimpleDiv(id) {
	answer = document.getElementById(id);
		answer.style.display = '';
		answer.focus();
};

/* SHOW & HIDE HELP DIV */
function showDivHelp(id) {
    if (document.getElementById) {
        el = document.getElementById(id);
        if (el.style.display == 'none') {
            document.getElementById('option' + id).src = conf_host + 'images/info.png';
            el.style.display = '';
        } else {
            document.getElementById('option' + id).src = conf_host + 'images/info.png';
            el.style.display = 'none';
        }
    }
};

/* CLEAR FIELD */
function clearField(obj) {
	if (obj.defaultValue==obj.value) obj.value = '';
};

/*#############################################################

SUBMIT BUTTON FUNCTION FROM

Name: Niceforms
Version: 0.9
Author: Lucian Slatineanu
URL: http://www.badboy.ro/

Feel free to use and modify but please provide credits.
#############################################################*/

var buttons = new Array();

function buttonHovers() {
	//get all buttons
	var elements = document.getElementsByTagName('input');
	var j = 0;
	for (var i1 = 0; i1 < elements.length; i1++) {
		if(elements[i1].type=='submit') {
			buttons[j] = elements[i1];
			++j;
		}
	}

	//add hover effects
	for (var i1 = 0; i1 < buttons.length; i1++) {
		buttons[i1].onmouseover = function() {this.className += "Hovered";}
		buttons[i1].onmouseout = function() {this.className = this.className.replace(/Hovered/g, "");}
	}
};


/* FOCUS INPUT FIELD */
function makeFocus() {
  var x=document.forms.govidForm
  x[0].focus()
};


/*******************
	TEXTAREA BY:
Author: Patrick Ryan
URL: http://www.agavegroup.com
*******************/
function prettyForms(){
		fixTextareas();
	};
	function appendParentsTo(currItem){
		//create the divs
		tl = document.createElement("div");
		br = document.createElement("div");
		bl = document.createElement("div");
		tr = document.createElement("div");

		if(document.all){							//IE
			//give them the proper class
			tl.className="frmShdwTopLt";
			br.className="frmShdwBottomRt";
			bl.className="frmShdwBottomLt";
			tr.className="frmShdwTopRt";
			//insert the top level div
			t1=currItem.insertAdjacentElement("BeforeBegin",tl);
		}else{										//FFX
			//give them the proper class
			tl.setAttribute("class", "frmShdwTopLt");
			br.setAttribute("class", "frmShdwBottomRt");
			bl.setAttribute("class", "frmShdwBottomLt");
			tr.setAttribute("class", "frmShdwTopRt");
			inputParent = currItem.parentNode;
			//insert the top level div
			tl = inputParent.insertBefore(tl, currItem);
		}

		//append children
		br = tl.appendChild(br);
		bl = br.appendChild(bl);
		tr = bl.appendChild(tr);
		//move input to child of divs
		tr.appendChild(currItem);
	};
	//apply look to textareas
	function fixTextareas(){
		textareas = document.getElementsByTagName("textarea")
		for(i=0;i<textareas.length;i++){
			appendParentsTo(textareas[i]);
		}
	};


/* STARS */
function fillStars(rating, user) {
  var user = document.getElementById(user);
  user.innerHTML = rating + '/5';
 };
 function clearStars(real_rating, user) {
  var user = document.getElementById(user);
  user.innerHTML = real_rating + '/5';
 };

/* HIDE ANSWER DIV */
function hideAnswerDivs(id) {
  var divsAnswerVote = getElementsIdsByClassName('answerVote', '', 'div');
  var divsAnswerVoteErr = getElementsIdsByClassName('answerVoteErr', '', 'div');
  for (var i = 0; i < divsAnswerVote.length; i++) {
    if (divsAnswerVote[i].id != id) {
      divsAnswerVote[i].style.display = 'none';
    }
  }
  for (var i = 0; i < divsAnswerVoteErr.length; i++) {
    if (divsAnswerVoteErr[i].id != id) {
      divsAnswerVoteErr[i].style.display = 'none';
    }
  }
};

/* ASSIGN BLUR ON HYPERLINKS */
function blurLinks() {
  theLinks = document.getElementsByTagName('a');
  for(i = 0; i < theLinks.length; i++) {
    theLinks[i].onfocus = function() { this.blur(); };
  }
};

/* ajax function which displays welcome message. */
 function AjaxWelcomeMessage(parameters,url) {
      http_request = false;
	  http_request = GetXmlHttpObject();
      http_request.open('POST', url, true);
	  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.onreadystatechange  = function() { 	  // if xmlhttp shows "loaded"
        if (http_request.readyState==4){
        // if "OK"
            if (http_request.status == 200){
				 var text = http_request.responseText;
                 document.getElementById("welcome_menu").innerHTML = text; 
                 
            }else{
                  alert("Problem retrieving data:" + http_request.statusText)
            }
        }
      }

	  http_request.send(parameters);
};

//function called when rating
function DisplayWelcomeMessage(session_user,cookie_user) {
  url = global_url_welcome + "?lcode=" + global_lcode;
  parameters = "cookie_user=" + cookie_user + "&session_user=" + session_user ;
  AjaxWelcomeMessage(parameters,url);
};
