String.prototype.wordWrap = function(m, b, c){
    var i, j, l, s, r;
    if(m < 1)
        return this;
    for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
            || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    return r.join("\n");
};

function create_form(id, uid, flag) {
  if (uid == 0) {
    display_sign_in_box("boxans_"+id)
    display_div('asd');
    return;
  }
  var html ='';
  var disp_obj = document.getElementById("ansbox_"+id);
  document.getElementById("ansbox_"+id).style.display = "block"
  html ='<div class="answer-box-post"><input type="hidden" id="uid" name="uid" value="'+uid+'" ><textarea rows="0" cols="0" id ="text_'+id+'"></textarea><span><img class="star" src="theme1/images/post-answer.gif" alt="Post" onclick="submit_form('+id+','+flag+')"/></span><span><img class="star" src="theme1/images/cancel.gif" alt="Post" onclick="hide_box(\'ansbox_'+id+'\')"/></span></div>';
  disp_obj.innerHTML = html;
}

function submit_form(id, flag, poll_show) {
  var uid = document.getElementById('uid').value;
  var answer = escape(trim(document.getElementById('text_'+id).value));
  if(answer == '') {
    alert("Please write answer. You can not post blank answer.")
    return;
  }
  url = base_url + "web/submitanswer.php?id="+id+"&uid="+uid+"&flag="+flag+"&poll_show="+poll_show;
  var asker_id = document.getElementById('asker_id').value;
  var category_id = document.getElementById('category_id').value;
  var question_id = document.getElementById('qes_id').value;
  var params = new Array(5);
  params['answer'] = answer;
  //params['asker_email'] = asker_email;
  params['asker_id'] = asker_id;
  params['category_id'] = category_id;
  params['question_id'] = question_id;

  get_loading_image("ansbox_"+id);
  id= id+'~'+flag;
  document.getElementById('ans_button0').disabled = true;
  document.getElementById('ans_button0').src = base_url + 'theme1/images/Wait_btn.gif';
  HTTPPost(url, params, answer_submited, id);
}


function answer_submited(data, http, id) {
  var str = id.split('~');
  id = str[0];
  flag = str[1]
  if(data) {
    if(data == 'noaccess') {
      alert('You have crossed your daily limit for posting answer');
      var html ='<span >Your answer has not been posted.</span>';
    } else if (data == 'notallowed') {
      alert('You have already answered this Question');
      var html ='<span >Your answer has not been posted.</span>';
    } else {
      var html ='Your answer has been posted.Thank you.';
      if(flag == 1) {
        var ans = data.split('~');
        answers = ans[0];
        count = ans[1];
        document.getElementById('inner_answer_container').innerHTML = unescape(answers);
        document.getElementById('answer_container_'+id).innerHTML = count;
      } else {
        document.getElementById('answer_container_'+id).innerHTML = unescape(data);
      }
    }
  } else {
    var html ='Your answer has not been posted.';
  }
  window.scrollTo(0, 100);
  //document.getElementById("ansbox_"+id).innerHTML = html;
	if(document.getElementById('ans_button0')) {
  	document.getElementById('ans_button0').disabled = false;
  	document.getElementById('ans_button0').src = 'theme1/images/ET_TOI/blue_answer.gif';
  }
  var email = data.split('~~');
  if (email[1]) {
    var content_id = data.split('~~~');
    var answer = data.split('~~~~');
    var ques_title = data.split('~~~~~');
    var login_name = data.split('~~~~~~');
    url1 = base_url + "web/send_notification_mail.php";
    var params = new Array(6);
    params['email'] = email[1];
    params['answer'] = answer[1];
    params['ques_title'] = ques_title[1];
    params['login_name'] = login_name[1];
    params['content_id'] = content_id[1];
    params['count'] = count;
    HTTPPost(url1, params, show_notification_mail);
    get_loading_image('mail_notification_container');
  } else {
    document.getElementById("ansbox_"+id).innerHTML = '<div class="nickname_form" ><span id="name_form" style="width:100%; float:left"><b>'+ html +'</b></span><span style = "width:100%; float:left;text-align:center;"><b><input type = "button" onclick = "reload_page_after_best_answer();" value = "OK"></b></span></div>';
  }

}

function show_notification_mail() {
   document.getElementById('mail_notification_container').innerHTML = 'Email has been sent successfully';
}


function textCounter(field,cntfield,maxlimit,id) {
  if (field.value.length > maxlimit)  {// if too long...trim it!
    field.value = field.value.substring(0, maxlimit);
    alert("Maximum limit is expired")
  } else {
    cntfield.value = maxlimit - field.value.length;
    document.getElementById(id).innerHTML = cntfield.value;
  }
}

function display_sign_in_box(id) {
  var obj = document.getElementById(id);
  var iframe_obj = document.getElementById('iframe_id');
  var posX = findPosX(obj);
  var posY = findPosY(obj);

  var iframe_posX = findPosX(iframe_obj);
  var iframe_posY = findPosY(iframe_obj);

  var disp_obj = document.getElementById('sign_in_box');
  disp_obj.style.position = 'absolute';
  disp_obj.style.top = (posY + 1) + 'px';
  //disp_obj.style.top = (posY - 5) + 'px';
  //disp_obj.style.left = (posX - 210) + 'px';
  disp_obj.style.left = (posX - 350) + 'px';

  disp_obj.style.display = 'block';

  iframe_obj.style.position = 'absolute';
  iframe_obj.style.top = (iframe_posY - 5) + 'px';
  iframe_obj.style.left = (iframe_posX - 210) + 'px';
 // iframe_obj.style.left = (iframe_posX + 200) + 'px';
  iframe_obj.style.display = 'block';

  document.getElementById('indiatimes_id').focus();
}

function display_sign_in_LEFT_box(id) {
  var obj = document.getElementById(id);
  var iframe_obj = document.getElementById('iframe_id');
  var posX = findPosX(obj);
  var posY = findPosY(obj);

  var iframe_posX = findPosX(iframe_obj);
  var iframe_posY = findPosY(iframe_obj);

  var disp_obj = document.getElementById('sign_in_box');
  disp_obj.style.position = 'absolute';
  disp_obj.style.top = (posY + 1) + 'px';
  disp_obj.style.left = (posX - 50) + 'px';
 //disp_obj.style.left = (posX) + 'px';
  disp_obj.style.display = 'block';

  iframe_obj.style.position = 'absolute';
  iframe_obj.style.top = (iframe_posY - 5) + 'px';
//  iframe_obj.style.left = (iframe_posX - 210) + 'px';
iframe_obj.style.left = (iframe_posX + 200) + 'px';
  iframe_obj.style.display = 'block';

  document.getElementById('indiatimes_id').focus();
}

function display_sign_in_INFOTECH_box(id) {
  var obj = document.getElementById(id);
  var iframe_obj = document.getElementById('iframe_id');
  var posX = findPosX(obj);
  var posY = findPosY(obj);

  var iframe_posX = findPosX(iframe_obj);
  var iframe_posY = findPosY(iframe_obj);

  var disp_obj = document.getElementById('sign_in_box');
  disp_obj.style.position = 'absolute';
  disp_obj.style.top = (posY + 1) + 'px';
  disp_obj.style.left = (posX + 10) + 'px';
 //disp_obj.style.left = (posX) + 'px';
  disp_obj.style.display = 'block';

  iframe_obj.style.position = 'absolute';
  iframe_obj.style.top = (iframe_posY - 5) + 'px';
//  iframe_obj.style.left = (iframe_posX - 210) + 'px';
iframe_obj.style.left = (iframe_posX + 200) + 'px';
  iframe_obj.style.display = 'block';

  document.getElementById('indiatimes_id').focus();
}

function display_sign_in_box1(id) {
  var obj = document.getElementById(id);
  var iframe_obj = document.getElementById('iframe_id');
  var posX = findPosX(obj);
  var posY = findPosY(obj);

  var iframe_posX = findPosX(iframe_obj);
  var iframe_posY = findPosY(iframe_obj);

  var disp_obj = document.getElementById('sign_in_box');
  disp_obj.style.position = 'absolute';
  disp_obj.style.top = (posY - 5) + 'px';
  disp_obj.style.left = (posX + 40) + 'px';
  disp_obj.style.display = 'block';

  iframe_obj.style.position = 'absolute';
  iframe_obj.style.top = (iframe_posY - 5) + 'px';
  iframe_obj.style.left = (iframe_posX - 210) + 'px';
  iframe_obj.style.display = 'block';

  document.getElementById('indiatimes_id').focus();
}

function close_signin_box() {
  document.getElementById('sign_in_box').style.display = 'none';
  document.getElementById('iframe_id').style.display = 'none';
}

function popup_box_open(id, content_id, uid,formtype,owner_id, category_id, submit_type) {
  if(uid == 0) {
    display_sign_in_LEFT_box(id)
    display_div('asd');
	  return;
  }
  var obj = document.getElementById(id);
  var posX = findPosX(obj)
  var posY = findPosY(obj)
  var disp_obj = document.getElementById('popup_box');
  disp_obj.style.position = 'absolute'
  disp_obj.style.top = (posY -5) + 'px'
  disp_obj.style.left = (posX) + 'px'
  disp_obj.style.display = 'block';
  if(formtype == 1) {
    if(uid == owner_id) {
      alert("You cannot report abuse on your own Question or Answer")
      return;
    }
    if (submit_type == 0) {
      var question_id = document.getElementById('qes_id').value;
    }
    url = base_url + "web/ajax/report_abuse.php?content_id="+content_id+"&category_id="+category_id+"&uid="+uid+"&owner_id="+owner_id+"&question_id="+question_id+"&submit_type="+submit_type;
  } else if(formtype == 2) {
    url = base_url + "web/ajax/send_email.php?content_id="+content_id;
  }
  document.getElementById('popup_box').innerHTML = '<img  src="' + base_url + 'theme1/images/loading.gif" />';
   HTTPPost(url,'', show_popup_box_form,formtype);
}

function show_popup_box_form(data,http, form_type) {
  document.getElementById('popup_box').innerHTML = data;
  if(form_type == 2) {
    document.getElementById('mail_link').innerHTML ='<a href = "'+document.getElementById('maillink').value+'" target="_blank">'+ document.getElementById('maillink').value.wordWrap(45, "\n", true)+'</a>';
  }
}

function setActionPath(base_url) {
  var rem = 0;
  if (document.login_form.remember.checked) {
    rem = 1;
  }
  var url = base_url + rem;
  url = URLEncode(url);
  url = "http://integra.indiatimes.com/Times/Logon.aspx?ru="+url+"&IS=9ca27b74-0c17-4241-aa7f-dd9174e5cea9&NS=my&HS=lyEEXqnzaJAxFZULMc1ib84P2Ik=";
  //alert("Action Path "+url);
  document.login_form.action=url;
  document.login_form.submit();
}

function setActionPathAstro(flag,base,base_url,text_area_id) {
	var rem = 0;
	if (flag==0){
		  if (document.Ask_Question.login.value == "") {
		  var urlb=base+ "?ref=askaAstroquestion"; 
		   document.Ask_Question.action=urlb;
		   document.Ask_Question.submit();
		  }else{ 
			  if (document.getElementById(text_area_id).value != '') { 
				save_question_answer(text_area_id, 'ques'); 
			  }
				  var url = base_url + rem;
				  url = URLEncode(url);
				   url = "http://integra.indiatimes.com/Times/Logon.aspx?ru="+url+"&IS=9ca27b74-0c17-4241-aa7f-dd9174e5cea9&NS=my&HS=lyEEXqnzaJAxFZULMc1ib84P2Ik=";
				  document.Ask_Question.action=url;
				  document.Ask_Question.submit();
				 }
	}else{ 
		  if (document.getElementById(text_area_id).value != '') { 

		  save_question_answer(text_area_id, 'ques');
		  }
	  var url = base_url + rem;
	  url = URLEncode(url);
	   url = "http://integra.indiatimes.com/Times/Logon.aspx?ru="+url+"&IS=9ca27b74-0c17-4241-aa7f-dd9174e5cea9&NS=my&HS=lyEEXqnzaJAxFZULMc1ib84P2Ik=";

	  document.Question.action=url;
	  document.Question.submit();
	 }

}



function URLEncode(url) {
  // The Javascript escape and unescape functions do not correspond
  // with what browsers actually do...
  var SAFECHARS = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	 "abcdefghijklmnopqrstuvwxyz" + "-_.!~*'()";
  var HEX = "0123456789ABCDEF";

  var plaintext = url;
  var encoded = "";
  for (var i = 0; i < plaintext.length; i++ ) {
    var ch = plaintext.charAt(i);
    if (ch == " ") {
        encoded += "+";				// x-www-urlencoded, rather than %20
    } else if (SAFECHARS.indexOf(ch) != -1) {
        encoded += ch;
    } else {
      var charCode = ch.charCodeAt(0);
      if (charCode > 255) {
          alert( "Unicode Character '" + ch + "' cannot be encoded using standard URL encoding.\n" + "(URL encoding only supports 8-bit characters.)\n" + "A space (+) will be substituted." );
          encoded += "+";
      } else {
          encoded += "%";
          encoded += HEX.charAt((charCode >> 4) & 0xF);
          encoded += HEX.charAt(charCode & 0xF);
      }
    }
  }
  return encoded;
}

function show_best_answer (data, http, content) {
  document.getElementById (content).innerHTML = data;
}

function select_answers (question_id,page,content) {
  url = base_url + "web/choose_best_answer.php?&qid="+question_id+"&page="+page+"&show_div_tag="+content;
  HTTPPost(url,'', show_next_prev_answer, content);
}

function save_question_answer (text_id, text_type) { 
  if (text_type == 'ques') {
    var text_data = document.getElementById(text_id).value;
  }
  if (text_type == 'answer') {
    var id ="text_" + text_id;
    var text_data = document.getElementById(id).value;
  }
  if (text_type == 'save_answer_id') {
    var text_data = '';
  }
  var params = new Array(1);
  params['text_data'] = text_data;
  url = base_url + "web/ajax/save_question.php?type="+text_type+"&id="+text_id;
  HTTPPost(url, params); 
	
}

function select_content(content, uid, page) {
  get_loading_image('question_answer_container');
  url = base_url + "web/show_question_answer.php?content="+content+"&uid="+uid+"&page="+page;
  HTTPPost(url,'', show_content, content);
}

function show_content(data, http, content) {
  document.getElementById('question_answer_container').innerHTML = data;
}

function show_next_prev_answer(data, http, content) {
  document.getElementById(content).innerHTML = data;
}

function select_tab_type (tab_type, show, hide) {
  if (tab_type == 'selected') {
    document.getElementById(show).style.display = 'block'
    document.getElementById(hide).style.display = 'none'
  } else {
    document.getElementById(show).style.display = 'none'
    document.getElementById(hide).style.display = 'block'
  }
}

function show_question(data, http, content) {
  document.getElementById('question_answer_container').innerHTML = data;
}

// function show_more_answer(question_id, page, uid, asker_id, sort_type, poll_show, category_id) { //alert(uid);
//   get_loading_image('inner_answer_container');
//   url = base_url + "web/answerlist.php?question_id="+question_id+"&page="+page+"&uid="+uid+"&asker_id="+asker_id+"&sort_type="+sort_type+"&poll_show="+poll_show + "&category_id=" + category_id;
//   HTTPPost(url,'', show_answer);
// }

function show_answer(data, http, id) {
  document.getElementById('inner_answer_container').innerHTML = data;
	//for adding  nic editor .
	if(document.getElementById('text_'+id) != null && id != undefined) {
		bkLib.onDomLoaded(function() { nicEditors.oneTextArea('text_'+id) });
	}
}

// function select_answerquestion(ques_type, uid, period, page) {
//   get_loading_image('inner_answer_container');
//   url = base_url + "web/ajax/answerquestion.php?ques_type="+ques_type+"&uid="+uid+"&page="+page+"&period="+period;
//   HTTPPost(url,'', show_answerquestion);
// }

// function show_answerquestion(data, http) { //alert(data);
//   document.getElementById('inner_answer_container').innerHTML = data;
// }

function set_rating(content_id, uid, vote, owner_id, type, category_id, asker_id) {
  if (uid == 0) {
    display_sign_in_box('star_container_'+content_id)
    display_div('asd');
    return;
  }
  if (uid == owner_id) {
    alert("You cannot rate your own Question or Answer")
    return;
  }
  if (type == 0) {
    var question_id = document.getElementById('qes_id').value ;
  }
  url = base_url + "web/ajax/rate.php?uid="+uid+"&content_id="+content_id+"&vote="+vote+"&category_id=" + category_id + "&asker_id=" + asker_id + "&type=" + type + "&question_id=" + question_id;
  HTTPPost(url,'', show_ratestars, content_id + '~' + type);
}

function show_ratestars(data, http, id) {
  var combine_type = id.split('~');
  if (combine_type[1] == 1) { //For Question
    document.getElementById('hide_rating_id').style.display = 'none';
    document.getElementById('show_rating_id').style.display = 'block';
    document.getElementById('star_container' + combine_type[0]).innerHTML = data;
  } else { //For answer
    document.getElementById('star_container_' + combine_type[0]).innerHTML = data;
  }
}

function selstar(val,con_name) {
  for(var x=1;x<=val;x++) {
    document['i'+con_name+x].src = base_url + "theme1/images/star2.gif";
  }
}

function remstar(val, con_name,newimg) {
  for(var x=1;x<=val;x++) {//alert(con_name)
    var newimg = document.getElementById('k'+con_name+x).value
    document['i'+con_name+x].src= base_url + "theme1/images/"+newimg;
  }
}

/**
* Only enable Javascript functionality if all required features are supported.
*/
function isJsEnabled() {
  if (document.jsEnabled == undefined) {
    // Note: ! casts to boolean implicitly.
    document.jsEnabled = !(
    !document.getElementsByTagName ||
    !document.createElement ||
    !document.createTextNode ||
    !document.getElementById);
  }
  return document.jsEnabled;
}

// Global Killswitch
if (isJsEnabled()) {

}

/**
* Make IE's XMLHTTP object accessible through XMLHttpRequest()
*/

if (typeof XMLHttpRequest == 'undefined') {
 XMLHttpRequest = function () {
   var msxmls = ['MSXML3', 'MSXML2', 'Microsoft']
   for (var i=0; i < msxmls.length; i++) {
     try {
       return new ActiveXObject(msxmls[i]+'.XMLHTTP')
     }
     catch (e) { }
   }
   throw new Error("No XML component installed!")
 }
}

function HTTPPost(uri, object, callback_function, callback_parameter) {
  var xmlhttp = new XMLHttpRequest();
  var bAsync = true;
  if (!callback_function)
    bAsync = false;
  xmlhttp.open('POST', uri, bAsync);
  xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  var form_contents = '';
  for (var i in object) {
    form_contents += (form_contents ? '&' : '') + i + '=' + escape(object[i]);
  }
  xmlhttp.send(form_contents);
  if (bAsync) {
    if (callback_function)
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4)
          callback_function(xmlhttp.responseText, xmlhttp, callback_parameter)
      }
    return true;
  } else
    return xmlhttp.responseText;

}

function show_aboutme(about_data,id) {
  var obj = document.getElementById(id)
  var posX = findPosX(obj)
  var posY = findPosY(obj)
  var disp_obj = document.getElementById('dashboard_popup_box');
  disp_obj.style.position = 'absolute'
  disp_obj.style.top = (posY) + 'px'
  disp_obj.style.left = (posX) + 'px'
  disp_obj.style.display = 'block';
  document.getElementById('dashboard_popup_box').innerHTML= '<div class="nickname_form" ><b class="fleft full-width">About me</b><b style="float:right; position:relative; top:-19px; right:1px;"><img src = "theme1/images/close.gif" onclick ="hide_box(\'dashboard_popup_box\')"></b>'+about_data+'</div>';
}

function bring_dashboard_popup(uid,id,frmtype) {
  var obj = document.getElementById(id)
  var posX = findPosX(obj)
  var posY = findPosY(obj)
  var disp_obj = document.getElementById('dashboard_popup_box');
  disp_obj.style.position = 'absolute'
  disp_obj.style.top = (posY) + 'px'
  disp_obj.style.left = (posX) + 'px'
  disp_obj.style.display = 'block';
  document.getElementById('dashboard_popup_box').style.display= 'block';
  if(frmtype == 1) {
    document.getElementById('dashboard_popup_box').innerHTML= '<div class="nickname_form" ><b>Change nick name</b><b style="float:right; position:absolute; top:10px; right:10px;"><img src = "theme1/images/close.gif" onclick ="hide_box(\'dashboard_popup_box\')"></b> <b style="width:100%; float:left;font-weight:normal">Enter name</b><span id="name_form" style="width:100%; float:left"><input type = "text" id="new_nickname" value=""/><input type="button" onclick="submit_nickname('+uid+')" value = "Save"></span></div>';
  }
  if(frmtype == 2) {
    document.getElementById('dashboard_popup_box').innerHTML= '<div  class="nickname_form" ><b>Change photo</b><b style="float:right; position:absolute; top:10px; right:10px;"><img src = "theme1/images/close.gif" onclick ="hide_box(\'dashboard_popup_box\')"style="float:right;"></b><b style="width:100%; float:left;font-weight:normal"> Select picture</b><span class="middle" style="width:100%; float:left"> <form method="POST" id="edit_pic" action="index.php?ref=submit_user_pic" enctype="multipart/form-data" target="file_frame"><input id= "user_image_id" type="file" size="10"  onchange="this.form.submit()" name="user_image"  /> <iframe name="file_frame" src="index.php?ref=submit_user_pic" style="display:none"></iframe><input type = "hidden" name="uid" value = "'+uid+'"><em style="float:right; padding:8px 5px 0 0; font-style:normal;">or <a href="index.php?ref=edit_profile">select an avatar</a></em></form></span></div>';
  }
}

function submit_nickname(uid) {
  var nickname = document.getElementById('new_nickname').value
	nickname = trim(nickname)
	if (nickname) {
	  url = base_url + "web/ajax/changenickname.php?uid="+uid+"&nickname="+nickname;
	  HTTPPost(url,'', show_nickname, 0);
	} else {
	  alert('Please enter nickname');
	}
}

function submit_best_answer(value, category_id) {
  if (value) {
    var new_value = value.split('|');
    answer_id = new_value[0];
    answerer_id = new_value[1];
    var qes_id = document.getElementById('qes_id').value;
    var uid = document.getElementById('uid').value;
    var asker_id = document.getElementById('asker_id').value;
    var output = 'best_answer' + answer_id + '~' + qes_id + '~~' + asker_id + '~~~' + category_id;
    url = base_url + "web/ajax/submit_best_answer.php?answer_id="+answer_id+"&answerer_id="+answerer_id+"&qes_id="+qes_id+"&uid="+uid;
    HTTPPost(url,'', thanks_show_best_answer, output);
  }
}

function show_nickname(data) {
	if(data) {
	  document.getElementById('nickname').innerHTML = data;
	  document.getElementById('nickname_top_left').innerHTML = data;
	}
	document.getElementById('change_name').style.display = 'block';
	document.getElementById('dashboard_popup_box').innerHTML = '<div class="nickname_form" ><b style="float:right; position:absolute; top:10px; right:10px;"><img src = "theme1/images/close.gif" onclick ="hide_box(\'dashboard_popup_box\')"></b> <span id = "name_form" style = "width:100%; float:left"><b>Your details have been updated. Thank you</b></span><span  float:left;text-align:center;"><b><input type="button" onclick = "hide_box(\'dashboard_popup_box\')" value = "OK"></b></span></div>'
}

function thanks_show_best_answer(data, http, content) {
	if(data) {
	  //document.getElementById('dashboard_point').innerHTML = data;
	 // document.getElementById('top_left_points').innerHTML = data;
	}
  var combined_value = content.split('~');
  var output_id = combined_value[0];
  var question_id = combined_value[1];
  var new_combined_value = content.split('~~');
  var asker_id = new_combined_value[1];
  var val = content.split('~~~');
  var category_id = val[1];
  document.getElementById(output_id).innerHTML = '<div class="nickname_form" ><span id="name_form" style="width:100%; float:left"><b>Thanks for choosing Your Favorite Answer</b></span><span style = "width:100%; float:left;text-align:center;"><b><input type = "button" onclick = "reload_page_after_best_answer(\''+question_id+'\', \''+asker_id+'\', \''+category_id+'\');" value = "OK"></b></span></div>';
}

function reload_page_after_best_answer(question_id, asker_id, category_id) {
//   url = base_url + "web/answerlist.php?question_id=" + question_id + "&asker_id=" + asker_id + "&category_id=" + category_id;
//   HTTPPost(url,'', show_answer);
//   get_loading_image('inner_answer_container');
//window.location = base_url +
 window.location.reload()
}

function create_argue_to_answer_form(content_id, uid, question_id, category_id, answerer_id) {
  if (uid == 0) {
    display_sign_in_box("argue_answer" + content_id);
    display_div('asd');
  } else {
    var posy = findPosY(document.getElementById("argue_answer" + content_id));
    url = base_url + "web/create_argue_to_answer_form.php?content_id=" + content_id + "&uid=" + uid + "&question_id=" + question_id + "&category_id=" + category_id+ "&answerer_id=" + answerer_id;
    HTTPPost(url,'', result_argue_to_answer, posy);
    get_loading_image('popup_question_comment');
  }
}

function result_argue_to_answer (data, http, content) {
  document.getElementById('popup_question_comment').innerHTML = data;
  document.getElementById('popup').style.top = content + 'px';
}

function submit_argue_comments_form(content_id, uid, question_id, category_id, answerer_id) {
  url = base_url + "web/submit_argue_comments_form.php";
  var comment = document.getElementById('argue_text').value;
  if (comment == '') {
    alert("Please write comment. You can not post blank comment.");
  } else {
    var params = new Array(3);
    params['comment'] = comment;
    params['content_id'] = content_id;
    params['uid'] = uid;
    params['question_id'] = question_id;
    params['category_id'] = category_id;
    params['answerer_id'] = answerer_id;
    var output = 'best_answer' + content_id;
    var callback_parameter = content_id + '~' + question_id + '~' + category_id;
    HTTPPost(url, params, result_submit_argue_comments, callback_parameter);
    get_loading_image(output);
  }
}

function result_submit_argue_comments(data, http, content) {
  if (data) {
    document.getElementById('popup').style.display = 'none';
    var combine_id = content.split('~');
    var content_id = combine_id[0];
    var question_id = combine_id[1];
    var category_id = combine_id[2];
    var asker_id = document.getElementById('asker_id').value;
    var output_id = 'best_answer' + content_id;
    document.getElementById(output_id).innerHTML = '<div class="nickname_form" ><span id="name_form" style="width:100%; float:left"><b>Your Comment has been posted.Thank You.</b></span><span style = "width:100%; float:left;text-align:center;"><b><input type = "button" onclick = "reload_page_after_best_answer(\''+question_id+'\', \''+asker_id+'\', \''+category_id+'\');" value = "OK"></b></span></div>';
  }
}

function trim(field) {
  value = field;
  while (value.charAt(value.length-1) == " ") {
    value = value.substring(0,value.length-1);
  }
  while (value.substring(0,1) ==" ") {
    value = value.substring(1,value.length);
  }
  return value;
}

function change_subcat(id,sel,is_admin) {//alert(sel)
  url = base_url + "web/ajax/fetch_subcat.php?catid="+id+"&sel="+sel+"&is_admin="+is_admin;
  HTTPPost(url,'', show_subcat, 0);
}

function show_subcat(data) {
  document.getElementById('sub_category').innerHTML= data;
}

function report_abuse(reporter,content_id, uid, submit_type, question_id, owner_id, category_id) {
  var abuse_comment = trim(document.getElementById('abuse_comment').value);
  
  if(abuse_comment) {
    var abuse_reason = document.getElementById('abuse_reason').value;
	
    get_loading_image('report_content1');
    var params = new Array(5);
    params['abuse_reason'] = abuse_reason;
    params['reporter'] = reporter;
	params['content_id'] = content_id;
    params['abuse_comment'] = abuse_comment;
    params['uid'] = uid;
    params['submit_type'] = submit_type;
    params['question_id'] = question_id;
    params['owner_id'] = owner_id;
	params['category_id'] = category_id;
    url = base_url + 'web/ajax/report_abuse_content.php';
    HTTPPost(url, params, after_send_report);
  } else {
    alert("Please enter comment");
  }
}
/**
 * Date:		28/04/09
 * Name:		Saumya
 * Description: Modified the code to correct the flow while reporting abuse
 **/
function after_send_report(data) {
  if(data) {
    if(data == 'no') {
      document.getElementById('report_content1').innerHTML = '<div style="float:left; width:100%;"><h4 style="float:left; width:100%; text-align:left;margin:0;padding:0; ">You have already reported this content as a  abuse</h4><span style="float:left; width:100%; text-align:center;"><input type="button" value="OK" onclick="hide_box(\'popup_box\')" /> </span></div>';
    } else {
      document.getElementById('report_content1').innerHTML = '<div style="float:left; width:100%;"><h4 style="float:left; width:100%; text-align:left;margin:0;padding:0; ">Your report has been sent</h4><span style="float:left; width:100%; text-align:center;"><input type="button" value="OK" onclick="hide_box(\'popup_box\');" /> </span></div>';
    }
    window.location.reload();
  }
}

function isValidEmail(email,required) {
  if (required==undefined) {   // if not specified, assume it's required
      required=true;
    }
    if (email==null) {
      if (required) {
        return false;
      }
      return true;
    }
    if (email.length==0) {
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
      return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
      return false;
    }
  return true;

}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

function send_email() {
  var email = document.getElementById('email').value
  var str = email.split(',');
  for(var i = 0; i<str.length; i++) {
    if(trim(str[i])) {
      if (! isValidEmail(str[i])) {
        alert(str[i]+' is not a valid Email id');
        return false;
      }
    }
  }
  email = trim(email)
  if (email) {
    var sender = document.getElementById('sender').value
    var maillink = escape(document.getElementById('maillink').value)
    var message = document.getElementById('message').value

    get_loading_image('report_content');
    url = base_url + "web/ajax/mailsend.php";
    var params = new Array(4);
    params['maillink'] = maillink;
    params['sender'] = sender;
    params['email'] = email;
    params['message'] = message;
    HTTPPost(url,params, after_send_email,0);
  } else {
    alert('Please enter mailid');
  }
}

function after_send_email(data) {
  document.getElementById('report_content').innerHTML = '<div style="float:left; width:100%;"><h4 style="float:left; width:100%; text-align:center;">Your email has been sent. Thank you</h4><span style="float:left; width:100%; text-align:center;"><input type="button" value="OK" onclick="hide_box(\'popup_box\')" /> </span></div>';
}

function content_report(content_type) {
  var obj = document.getElementById('report1')
  obj.options.length = 0;
  if (content_type == 'all') {
    var array = Array('All', 'Abused');
    for(i=0; i<2; i++) {
      var option1 = new Option(array[i]);
      obj.options[i] = option1;
      obj.options[i].value = array[i];
    }
  } else if (content_type == 'answer') {
    var array = Array('All', 'Abused', 'Hot Answers');
    for(i=0; i<3; i++) {
      var option1 = new Option(array[i]);
      obj.options[i] = option1;
      obj.options[i].value = array[i];
    }
  } else if (content_type == 'question') {
    var array = Array('All', 'Abused', 'Hot Questions', 'Bizzare' , 'Unanswered Questions');
    for(i=0; i<5; i++) {
      var option1 = new Option(array[i]);
      obj.options[i] = option1;
      obj.options[i].value = array[i];
    }
  }
}

function hide_box(id) {
  document.getElementById(id).innerHTML = '';
}

function hide_div(id) {
	document.getElementById(id).style.display = 'none';
}

function hide_output_box(id) {
  document.getElementById(id).innerHTML = '';
	document.getElementById(id).style.display = 'none'
	$(".hide_show_tag").show();
	$(".more_answers").hide();
}


function change_selected(sel_id, blank_id) {
	document.getElementById(sel_id) . className = 'active';
	document.getElementById(blank_id) . className = '';
  if (sel_id == 'ask_ques') {
    document.getElementById('question_box') . className = 'pointer_bottom';
    document.getElementById('search_box') . className = 'no-bg';
  }
  if (sel_id == 'search_ques') {
    document.getElementById('search_box') . className = 'pointer_bottom';
    document.getElementById('question_box') . className = 'no-bg';
  }
}

function detect_isie6() {
if (typeof document.body.style.maxHeight != 'undefined') {
return false
// IE 7, mozilla, safari, opera 9

} else {
return true
// IE6, older browsers
}
}

function show_taginfo(id) {
  var obj = document.getElementById(id)
  var posX = findPosX(obj)
  var posY = findPosY(obj)
  var disp_obj = document.getElementById('tag_popup_box');
  disp_obj.style.position = 'absolute'
  disp_obj.style.top = (posY ) + 'px'
  disp_obj.style.left = (posX) + 'px'
  disp_obj.style.display = 'block';
  document.getElementById('tag_popup_box').innerHTML= "<div class='nickname_form' style='width:400px;' ><b class='fleft full-width' style='text-decoration:underline;'>What's a tag</b><b style='float:right; position:relative; top:-19px; right:1px;'><img src = 'theme1/images/close.gif' onclick ='hide_box(\"tag_popup_box\")'></b><br>Tags are keywords/ short phrases that you can add to questions to make them easier for you and others to find.<br>For example, if your question is:<br>Q. How many films has Shahrukh Khan acted in?<br>The tags can be: Shahrukh Khan, bollywood, hindi films etc.<br><br>As more people tag an item with the same word, the tag will grow larger and bolder.  When you see a giant tag, you can be sure that the word is in some way relevant to the item it is being used to describe.<br><br>The more you tag, the more you share!</div>";
}

function checksubmit_ques() {
  var txt_value = document.getElementById('input_tag').value
  var str = txt_value.split(',');
  if(str.length > 10) {
    alert('You can not enter more than 10 tag');
    return false;
  } else {
    return true
  }
}

function fetch_mynetwork(uid, page) {
  get_loading_image('view_all_my_network');
  url = base_url + "web/ajax/fetch_mynetwork.php?&uid="+uid+"&page="+page;
  HTTPPost(url,'', show_my_network, 0);
}

function show_my_network(data, http, check_delete) {
  if (check_delete == 'delete_friend') {
    alert ('Member Deleted Successfully');
  }
  document.getElementById('view_all_my_network').innerHTML = data;
}

function delete_member(uid, page) {
  if (confirm("Are you sure you want to delete these member from your network?")) {
    var check = '';
    var noncheck = '';
    var inputs = document.getElementsByTagName('input');
    for (i = 0; input = inputs[i]; i++) {
      if (input && input.type == 'checkbox') {
        if(input.checked == true ) {
          check += input.value + ',';
        }
      }
    }
    if(check) {
      url = base_url + "web/ajax/fetch_mynetwork.php?&uid="+uid+"&page="+page+"&removefr="+check;
      HTTPPost(url,'', show_my_network, 'delete_friend');
    } else {
      alert('You have not selected any member.Please first select any member.')
    }
  }
}

function set_tag_home(id,val) {
  var check = document.getElementById('check_'+id).checked;
  if(check) {
    var is_home = 1;
  } else{
    var is_home = 0;
  }
  url = base_url + "web/ajax/set_tag_onhome.php?&id="+id+"&is_home="+is_home;
  HTTPPost(url,'', '', 0);
}

function display_div(tab) {
  document.getElementById(tab).style.display = 'block';
}

function show_edit_box(id) {
  var check = document.getElementById('check_'+id).checked;
  if(check) {
    document.getElementById('edit_box_'+id).style.display = 'block';
  } else {
    document.getElementById('edit_box_'+id).style.display = 'none';
  }
}

function cancel_edit_box(id) {
  document.getElementById('check_'+id).checked = false;
  document.getElementById('edit_box_'+id).style.display = 'none';
}

function save_abuse_category(id) {
  var category = document.getElementById('edit_cat_'+id).value;
  var desc = document.getElementById('edit_desc_'+id).value;
  var check = document.getElementById('edit_active_stat_'+id).checked;
  var sno = document.getElementById('cat_sno_'+id).value;
  if(check) {
    var stat = 1;
  } else {
    var stat = 0;
  }
  var url = base_url + "web/ajax/edit_abuse_category.php?&id="+id+"&category="+category+"&desc="+desc+"&stat="+stat+"&sno="+sno;
  HTTPPost(url,'', after_save_abuse_category, id);
}

function after_save_abuse_category(data, http, id) {
  $("#cat_row_container_" + id).html(data);
  //document.getElementById('cat_row_container_'+id).innerHTML = data;
  cancel_edit_box(id);
}

function change_tag(id) {
  var html = '';
  var val =  document.getElementById('tag_val_'+id).value;
  html = '<input name="abc" id = "tag_new_val'+id+'" type="text"  value="'+val+'" /> <input type="button" value="Save" onclick="save_tag_content('+id+')"/> <input type="button" value="Cancel" onclick="close_tag_box('+id+')" />'
  document.getElementById('tag_cont_'+id).innerHTML = ''
  document.getElementById('tag_cont_'+id).style.display = 'none';
  document.getElementById('input_tag_'+id).style.display = 'block';
  document.getElementById('input_tag_'+id).innerHTML = html;
}

function close_tag_box(id) {
  var val =  document.getElementById('tag_val_'+id).value;
  document.getElementById('input_tag_'+id).innerHTML = '';
  document.getElementById('input_tag_'+id).style.display = 'none';
  document.getElementById('tag_cont_'+id).style.display = 'block';
  document.getElementById('tag_cont_'+id).innerHTML = val;
}

function save_tag_content(id) {
  var val =  document.getElementById('tag_new_val'+id).value;
  url = base_url + "web/ajax/edit_tag_content.php?&id="+id+"&val="+val;
  HTTPPost(url,'', after_save_tag_content, id);
}

function after_save_tag_content(data,http,id) {
  document.getElementById('tag_val_'+id).value = data;
  document.getElementById('tag_cont_'+id).style.display = 'block';
  document.getElementById('tag_cont_'+id).innerHTML = data;
  document.getElementById('input_tag_'+id).innerHTML = '';
  document.getElementById('input_tag_'+id).style.display = 'none';
}

function set_hot_ans(id,chk){
  var stat=0;
  if(chk) {
     stat = 1;
  } else {
     stat = 0;
  }
  //alert(stat);
  url = base_url + "web/ajax/set_hot_content.php?id="+id+"&stat="+stat;
  //alert(url);
  HTTPPost(url,'', after_save_hotans, id);
}

function set_bizzare (id,chk){
  var stat = 0;
  if(chk) {
     stat = 1;
  } else {
     stat = 0;
  }
  //alert(stat);
  url = base_url + "web/ajax/set_bizzare_content.php?&id="+id+"&stat="+stat;
  HTTPPost(url,'', after_save_hotans, id);
}

function after_save_hotans(data) {
  if(data == 0) {
    alert("This is already a featured answer");
  } else {
    document.getElementById('hot_ans_mas').innerHTML = data;
  }
}

function check_friend(usid) {
  if (usid == 0) {
    display_sign_in_box("user_photo")
    display_div('asd');
    return false;
  }
}

function bring_level_points_popup(uid,frmfield) {
  var id = "change_img_link" + uid;
  var dispid = "dashboard_popup_box" + uid

  var obj = document.getElementById(id)

  var posX = findPosX(obj)
  var posY = findPosY(obj)
  var disp_obj = document.getElementById(dispid);
  disp_obj.style.position = 'absolute'
  disp_obj.style.top = (posY) + 'px'
  disp_obj.style.left = (posX) + 'px'
  disp_obj.style.display = 'block';
  disp_obj.style.display= 'block';

  frm = document.forms["edit_pic12"];


  frm.action = 'index.php?ref=submit_level_point_pic';
  frm.encoding = 'multipart/form-data';
  frm.target = 'file_frame';

  if (navigator.appName == "Microsoft Internet Explorer") {
    disp_obj.innerHTML= '<div class="nickname_form" style="position:absolute; top:10px; right:-40px; background:#fff" ><b>Change photo</b><b style="float:right; position:absolute; top:10px; right:10px;"><img src = "theme1/images/close.gif" onclick ="hide_box(\''+dispid+'\')"style="float:right;"></b><b style="width:100%; float:left;font-weight:normal"> Select picture</b><span style="float:left"> <input type="hidden" name="fieldname" value="' + frmfield + '" /><input type="hidden" name="fieldid" value="' + uid + '" /><input style="width:100%;" id= "user_image_id" type="file" size="15"  onchange="frm.submit()" name="user_image"  /> <iframe name="file_frame"  style="display:none"></iframe><input type = "hidden" name="uid" value = "'+uid+'"></span></div>';
  } else {
    disp_obj.innerHTML= '<div class="nickname_form" style="position:absolute; top:10px; right:-40px; background:#fff" ><b>Change photo</b><b style="float:right; position:absolute; top:10px; right:10px;"><img src = "theme1/images/close.gif" onclick ="hide_box(\''+dispid+'\')"style="float:right;"></b><b style="width:100%; float:left;font-weight:normal"> Select picture</b><span style="float:left"> <form method="POST" id="edit_pic" action="index.php?ref=submit_level_point_pic" enctype="multipart/form-data" target="file_frame"><input type="hidden" name="fieldname" value="' + frmfield + '" /><input type="hidden" name="fieldid" value="' + uid + '" /><input id= "user_image_id" type="file" size="10"  onchange="this.form.submit()" name="user_image"  /> <iframe name="file_frame" src="index.php?ref=submit_level_point_pic" style="display:none"></iframe><input type = "hidden" name="uid" value = "'+uid+'"></form></span></div>';
  }
}





function doSubmit(){
	frm = document.forms["edit_pic12"];
  frm.action = '';
  frm.encoding = 'application/x-www-form-urlencoded';
  frm.target = '';
  frm.submit();
}

function global_form_validation() {
  if (!CheckInput('Open_period.open_days','Default Days') || !CheckNumber('Open_period.open_days','Default No. of Days','','int') )
    return false;
  }


//******************************************CHECKS  INPUT FORM ITEMS ARE ENTERED********************************
function CheckInput ( input,name,alt ){
  var input = eval ( "document." + input );

  if ( Boolean ( input ) ) {
    //trim leading and trailing spaces//
    string = trim ( input.value )
    var txt = ( alt ) ? alt : "Please provide the relevant information for this field.";
    if ( isWhitespace ( string ) ) {
      alert ( "\"" + name + "\" IS EMPTY\n----------\n" + txt );
      input.focus();
      return false;
    }
    input.value = string
  } return true
}
//*************************************End of CheckInput Function********************************************************



//FORM VALIDATOR FUNCTIONS//
function isEmpty(s){ return ((s == null) || (s.length == 0)) }
function isWhitespace(s){
    var i;
    var whitespace = " \t\n\r";
  if (isEmpty(s)) return true;
  for (i = 0; i < s.length; i++){
    var c = s.charAt(i);
    if (whitespace.indexOf(c) == -1) return false;
  } return true
}



function CheckNumber(input,name,req,type,uplimit,lowlimit) {
  var req = (req) ? req : 'req'

  if( (req != '')  && !CheckInput(input,name))
    return false
  var input = eval("document." + input);
  var lowlimit = (lowlimit) ? lowlimit : 0
  var uplimit = (uplimit) ? uplimit : 10000000000
  var type = (type) ? type : 'float'
  var flag='false';


  if(Boolean(input)) {
    var value=input.value;
    if(!isNaN(value) && value != 0 && (CheckRange(value,lowlimit,uplimit)))
      if(type=='int' && (value.indexOf('.') > 0 ))
        flag='false'
      else
        flag='true'

    if(flag=='false') {
      alert("\"" + name + "\" IS Not VALID\n----------\nPlease provide the relevant information for this field.");
      input.focus(); return false;
    }
    else
      return true
  }
}
function CheckRange(val,lowlimit,uplimit) {
  if(val >= lowlimit && val <= uplimit)
    return true;
  else
    return false;
}

function check_question_submit(uid, id) {
  if(uid == 0) {
    display_sign_in_box("ans_button"+id);
    display_div('asd'); 

    save_question_answer(id, 'save_answer_id');
    return false;
  }
  return true;
}

function check_loggedin_user(uid, id) {
  if(uid == 0) {
    display_sign_in_box("ans_button"+id);
    display_div('asd');
    return false;
  }
  return true;
}

function doHandleEnterKeyStroke(uid, evt, id, form_id, text_area_id) {
  var keyCode = document.layers ? evt.which : document.all ? event.keyCode : document.getElementById ? evt.keyCode : 0;
  if (!evt) evt=window.event;
  if (evt.keyCode == 13) { 

    save_question_answer(text_area_id, 'ques');
    var check = check_loggedin_user(uid ,id)
    if (check) {
      document.getElementById(form_id).submit();
    }
  }
  return false;
}

function tag_search_onenterpress(evt, form_id) {
  var keyCode = document.layers ? evt.which : document.all ? event.keyCode : document.getElementById ? evt.keyCode : 0;
  if (!evt) evt=window.event;
  if (evt.keyCode == 13) {
    submit_serach_form();
    document.getElementById(form_id).submit();
  }
  return false;
}

function change_header_tabs(val) {
  for (var inc = 1 ; inc <= 5 ; inc++) {
    if (document.getElementById('header_page_tabs' + inc)) {
      document.getElementById('header_page_tabs' + inc).className = '';
      document.getElementById('header_pointer' + inc).className = '';
    }
  }
  document.getElementById('header_page_tabs' + val).className = 'pointer';
  document.getElementById('header_pointer' + val).className = 'active';
}

function change_my_page_class(val) {
  for (var inc = 1 ; inc <= 5 ; inc++) {
    if (document.getElementById('my_page_pointer' + inc)) {
      document.getElementById('my_page_pointer' + inc).className = '';
      document.getElementById('my_page_active' + inc).className = '';
    }
  }
  document.getElementById('my_page_pointer' + val).className = 'pointer';
  document.getElementById('my_page_active' + val).className = 'active';
}

function change_my_page_tabs(tab1, tab2, tab3, tab4, tab5) {
  if (document.getElementById('show_hide_functionalities')) {
    if (tab1 == 'social_profile') {
      display_div('show_hide_functionalities');
    } else {
      hide_div('show_hide_functionalities');
    }
  }
  if (document.getElementById(tab1)) {
    document.getElementById(tab1).style.display = 'block';
  }
  if (document.getElementById(tab2)) {
    document.getElementById(tab2).style.display = 'none';
  }
  if (document.getElementById(tab3)) {
    document.getElementById(tab3).style.display = 'none';
  }
  if (document.getElementById(tab4)) {
    document.getElementById(tab4).style.display = 'none';
  }
  if (document.getElementById(tab5)) {
    document.getElementById(tab5).style.display = 'none';
  }
}

function submit_question_form(allow) {
  document.getElementById('submit_question').value='Wait...';
  document.getElementById('submit_question').disabled=true;
  if(allow == 1)fb_reg('q_title');
  setTimeout("document.getElementById('question_form_data').submit()",5000);
}

function form_submit(uid, id, form_id, text_area_id, language_id) {
//   if (language_id != 1){
//     var hindi_text = Quill.getLanguageText('quillDiv1');
//     document.getElementById('q_title').value = hindi_text;
//   }
  if(uid == 0) {
    if (document.getElementById(text_area_id).value != '') { 

      save_question_answer(text_area_id, 'ques');
    }
    display_sign_in_box("ans_button"+id);
    display_div('asd');
  } else {
    document.getElementById(form_id).submit();
  }
}

function set_focus(question_id) {
  var ques_id = 'text_' + question_id;
  if (document.getElementById(ques_id)) {
    document.getElementById(ques_id).focus();
  } else {
    alert("You have already answered this question.Please edit your answer if you want to add more views.");
  }
}

function check_answer (question_id, uid) {
  if (uid == 0) {
    display_sign_in_box("ans_button"+0);
    display_div('asd');
    return false;
  } else {
    return true;
  }
}

function save_session_answer (question_id, language_id,allow) { 
   if(allow == 1) { fb_reg('text_'+question_id); }
    setTimeout("save_question_answer(" + question_id + ", 'answer')",7000);
}

function check_save_answer (question_id, uid, poll_show) {
  if (!check_loggedin_user(uid, 0)) {
    var answer_id = 'text_' + question_id;
    if (document.getElementById(answer_id).value != '') {
	
      setTimeout("save_question_answer(" + question_id + ", 'answer')",7000);
    }
  } else {
    var captcha_text = trim(document.getElementById('captcha_text').value);//alert(captcha_text);
    if(captcha_text == '') {
      alert("Please enter valid code.");
      return;
    } else {
        varify_captcha(captcha_text, question_id, poll_show);
    }
    /*if (varify) {
      submit_form(question_id,'1');
    } */
  }
}

function varify_captcha(formName,captcha_text, question_id, poll_show) {
  url = base_url + "web/ajax/varify_captcha.php";
  var params = new Array(1);
  params['captcha_text'] = captcha_text;
	if (question_id && poll_show) {
		var combine_id = question_id + '~' + poll_show;
	} else {
		var combine_id = 0;
	}
	combine_id = combine_id + '~' + formName;
	//alert(combine_id);
  HTTPPost(url, params, result_varify_captcha, combine_id);
}

function result_varify_captcha(data, http, combineid) {
	var combine_id = combineid.split('~');
	//alert('data  '+ data + "   " + combineid);
  if (data == 'Varified') {
		if (combine_id[0] != 0) {
			var id = combine_id[0].split('~');
      //submit_form(id[0], '1', id[1]);
     	//document.answer_form.submit();
		} else {
			eval("document."+combine_id[1]+".submit()");
			//alert('form submit');
		}
  } else {
    alert("The letters you typed don't match the letters that were shown in the picture");
  }
}

function setHomepage(what, url) {
  if (navigator.appName == 'Microsoft Internet Explorer' && document.getElementById) {
    setHomepageExplorer(what, url);
  } else if (document.layers || document.getElementById) setHomepageNetscape(what, url);
    return false;
}

function setHomepageNetscape(what, url) {
  var warn = 'Due to Netscapes security handling, this page will show you a dialog with a warning.' + 'If you do not wish to grant this site the access to ' + 'your browser settings, you can manually copy ' + 'http://qna.indiatimes.com and paste it in the location field in ' + 'Edit|Preferences|Navigator.';
  if (confirm(warn)) {
    netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesWrite");
    navigator.preference('browser.startup.homepage', url);netscape.security.PrivilegeManager.disablePrivilege("UniversalPreferencesWrite");
  }
}

function setHomepageExplorer(what, url) {
  what.style.behavior = 'url(#default#homepage)';
  what.setHomePage(url);
}

function show_drop_down_categories(image, widget_page) {
  if (image == 'plus') {
    url1 = base_url + "web/ajax/show_all_categories_drop_down.php";
    var params = new Array(1);
    params['widget_page'] = widget_page;
    HTTPPost(url1, params, show_categories_drop_down);
    get_loading_image('categories_drop_down_menu');
  } else {
    document.getElementById('get_plus_image').style.display = 'block';
    document.getElementById('get_minus_image').style.display = 'none';
    document.getElementById('categories_drop_down_menu').innerHTML = '';
    document.getElementById('categories_drop_down_menu').style.display = 'none';
  }
}

function show_categories_drop_down(data,http) {
  document.getElementById('get_plus_image').style.display = 'none';
  document.getElementById('get_minus_image').style.display = 'block';
  document.getElementById('categories_drop_down_menu').style.display = 'block';
  document.getElementById('categories_drop_down_menu').innerHTML = data;
}

function cancel_submit_action (type) {
   document.getElementById(type).style.display = 'none';
}

function change_active_inactive_tab(tab1, tab2, tab3) {
  if (document.getElementById('change_tab_widget')) {
    if (document.getElementById('change_tab_widget').value != '') {
      var color_code_widget = document.getElementById('change_tab_widget').value;
      if (tab1 == 'recent_ques') {
        document.getElementById('header_question').style.background = color_code_widget;
        document.getElementById('header1_question').style.background = 'none';
        document.getElementById('header2_question').style.background = 'none';
      } else if (tab1 == 'unanswered_ques') {
        document.getElementById('header1_question').style.background = color_code_widget;
        document.getElementById('header_question').style.background = 'none';
        document.getElementById('header2_question').style.background = 'none';
      } else {
        document.getElementById('header2_question').style.background = color_code_widget;
        document.getElementById('header1_question').style.background = 'none';
        document.getElementById('header_question').style.background = 'none';
      }
    } else if (tab1 && tab2 && tab3) {
      document.getElementById(tab1).className = 'active';
      document.getElementById(tab2).className = '';
      document.getElementById(tab3).className = '';
    }
  } else {
    if (tab1 && tab2 && tab3) {
      document.getElementById(tab1).className = 'active';
      document.getElementById(tab2).className = '';
      document.getElementById(tab3).className = '';
    }
  }
}

function edit_question_description_form(content_id, answer_count) {
//   url = base_url + "web/ajax/edit_question_description_form.php";
//   var params = new Array(4);
//   params['content_id'] = content_id;
//   params['question_text'] = document.getElementById('question_title').innerHTML;
//   if (document.getElementById('question_body')) {
//     params['question_desc'] = document.getElementById('question_body').innerHTML;
//   }
//   params['answer_count'] = answer_count;
//   get_loading_image('edit_question_desc');
//   HTTPPost(url, params, result_edit_question_description_form);
  display_div('edit_question_desc');
  if (answer_count == 0) {
    document.getElementById('q_title').value = trim(document.getElementById('question_title').innerHTML);
  }
  document.getElementById('ques_desc').value = trim(document.getElementById('question_body').innerHTML);
  //document.getElementById('q_title').style.width = '301px';
}

function result_edit_question_description_form(data) {
  document.getElementById('edit_question_desc').innerHTML = data;
}

function submit_question_description_form(content_id, answer_count) {
  if (document.getElementById('q_title')) {
    var get_submited_text = document.getElementById('q_title').value;
    if (get_submited_text == '') {
      alert("Please write question. You can not post blank question.");
      return;
    }
  }
  
  var get_submited_desc = document.getElementById('ques_desc').value;
  /**
	 * Date:		29/04/09
	 * Name:		Saumya
	 * Description: Modified the code to add functionality for editing question title and other details
**/
  
  var get_submited_subcat = "";
  var get_submited_cat = "";
  var get_submited_tag ="";
  if(document.getElementById('category_id')){
	   get_submited_cat = document.getElementById('category_id').value;
  }
  
  if(document.getElementById('sub_category_id')){
	 get_submited_subcat = document.getElementById('sub_category_id').value;
  }
  
  if(document.getElementById('input_tag')){
	   get_submited_tag = document.getElementById('input_tag').value;
  }
	  
	  
  
  var params = new Array(7);
  params['content_id'] = content_id;
  params['get_submited_text'] = get_submited_text;
  params['get_submited_desc'] = get_submited_desc;
  /**
	 * Date:		29/04/09
	 * Name:		Saumya
	 * Description: Modified the code to add functionality for editing question title and other details
**/
  params['get_submited_cat'] = get_submited_cat;
  params['get_submited_subcat'] = get_submited_subcat;
  params['get_submited_tag'] = get_submited_tag;
  params['answer_count'] = answer_count;
  url = base_url + "web/ajax/submit_question_description_form.php";
    //get_loading_image('edit_question_desc');
  HTTPPost(url, params, result_submit_question_description_form);
}

function result_submit_question_description_form(data) {
  var combine_text = data.split('~!~');
  
  if (combine_text[0] != '') {
    document.getElementById('question_title').innerHTML = combine_text[0];
  }
  if (document.getElementById('question_body')) {
    if (combine_text[1]!= '') {
      if (document.getElementById('show_hide_desc')) {
        document.getElementById('show_hide_desc').style.display = 'block';
      }
    }
  } 
  hide_div('edit_question_desc');
  document.getElementById('question_body').innerHTML = combine_text[1];
	if (combine_text[2] == 0) {
		window.location = base_url;
	}
  if (combine_text[1] == '') {
    if(document.getElementById('desc_title')) {
      document.getElementById('desc_title').innerHTML = '';
    }
    if(document.getElementById('show_hide_desc')) {
      document.getElementById('show_hide_desc').style.display = 'none';
    }
  }
}

function fetch_stars_of_month (month) {
  url = base_url + "web/ajax/fetch_stars_of_month.php?month=" + month;
  get_loading_image('show_hide_view_all_som');
  HTTPPost(url, '', result_fetch_stars_of_month);
}

function result_fetch_stars_of_month(data) {
  document.getElementById('show_hide_view_all_som').innerHTML = data;
}

function get_searchresultcategory(id, type, answer_button_path) {
  get_loading_image('question');
  if (type == 'category') {
    url = base_url + "web/ajax/search_result_category.php?category_id=" + id;
  } else if (type == 'channel') {
    url = base_url + "web/ajax/search_result_category.php?channel_id=" + id + "&answer_button_path=" + answer_button_path;
  }
  HTTPPost(url,'', show_searchresultcategory);
}

function select_searchresultcategory(id, ques_type, type, answer_button_path, page) {
  get_loading_image('question');
  if (type == 'category') {
    url = base_url + "web/ajax/search_result_category.php?category_id=" + id + "&ques_type=" + ques_type + "&page=" + page;
  } else if (type == 'channel') {
    url = base_url + "web/ajax/search_result_category.php?channel_id=" + id + "&ques_type=" + ques_type + "&answer_button_path=" + answer_button_path + "&page=" + page;
  }
  HTTPPost(url,'', show_searchresultcategory);
}

function show_searchresultcategory(data) {
  document.getElementById('question').innerHTML = data;
}

function submit_serach_form(URL) {
	var search_tags = document.getElementById('search_tags').value;
	if (search_tags != '') {
		if(document.getElementById('tag_radio_button').checked) {
			document.Search.action = URL+'index.php?ref=searchresulttag';
			document.Search.submit();
		}
		if(document.getElementById('google_radio_button').checked) {
			document.Search.action = URL+'index.php?ref=searchresult';
			document.Search.submit();
		}
	} else {
		alert('Please enter a tag');
		return;
	}
}

function show_hide_answer_widget_page (plus_minus_image_id1, plus_minus_image_id2, widget_answer_id, show_answer) {
  document.getElementById(plus_minus_image_id1).style.display = 'block';
  document.getElementById(plus_minus_image_id2).style.display = 'none';
  if (show_answer) {
    document.getElementById(widget_answer_id).style.display = 'block';
  } else {
    document.getElementById(widget_answer_id).style.display = 'none';
  }

}

function change_widget_category_ques(category_id, category_name) {
  get_loading_image('widget_category_questions_id');
  url = base_url + "web/ajax/change_widget_cagtegory_questions.php?category_id=" + category_id;
  var params = new Array(1);
  params['category_name'] = category_name;
  HTTPPost(url, params, result_widget_category_question);
}

function result_widget_category_question(data) {
  var str = data.split('~~~');
  document.getElementById('widget_category_questions_id').innerHTML = str[0];
  document.getElementById('header_category').innerHTML = str[1];
}

function change_widget_category_tab (tab1, tab2) {
  document.getElementById(tab2).style.display = 'none';
  document.getElementById(tab1).style.display = 'block';
}

function change_widget_category_tab_display (tab1, tab2) {
  document.getElementById(tab1 + '_active').className = 'active';
  document.getElementById(tab2 + '_active').className = '';
}


function sort_answers (question_id, sort_type, asker_id, poll_show, category_id,url) {
//   url = base_url + "web/answerlist.php?question_id=" + question_id + "&sort_type=" + sort_type+ "&asker_id=" + asker_id + "&poll_show=" + poll_show + "&category_id=" + category_id;
//   HTTPPost(url,'', result_sort_answers);
//   get_loading_image('inner_answer_container');
  //window.location.reload()
  window.location = url + "&sort_type=" + sort_type;
}
function result_sort_answers (data) {
  document.getElementById('inner_answer_container').innerHTML = data
}

function get_popular_ques_per_days(period) {
  get_loading_image('pop');
  url = base_url + "web/ajax/popular_question_per_days.php?period=" + period;
  HTTPPost(url,'', result_get_popular_ques_per_days);
}

function result_get_popular_ques_per_days (data) {
  document.getElementById('pop').innerHTML = data
}

function edit_answer_form(content_id, uid, question_id, ans_id, type) {
  if (type == 'answer') {
      var id = 'popup';
    } else {
      var id = 'popup_expert';
    }
  if (uid == 0) {
    display_sign_in_box("edit_answer" + content_id + type);
    display_div('asd');
  } else {
    var posy = findPosY(document.getElementById("edit_answer" + content_id + type));
    display_div(id);
    document.getElementById(id).style.top = posy + 'px';
    document.getElementById('edit_text_' + type).value = trim(document.getElementById(ans_id).innerHTML);
    
// 		var ans = trim(document.getElementById(ans_id).innerHTML);
//     var posy = findPosY(document.getElementById("edit_answer" + content_id));
//     url = base_url + "web/edit_answer_form.php";
// 		var param = new Array(3);
//     param['content_id'] = content_id;
//     param['uid'] = uid;
//     param['question_id'] = question_id;
//     param['answer'] = ans;
//     param['ans_id'] = ans_id;
//     HTTPPost(url, param, result_edit_answer_form, posy);
//     get_loading_image('popup_question_comment');
  }
}

function result_edit_answer_form (data, http, content) {
  document.getElementById('popup_question_comment').innerHTML = data;
  document.getElementById('popup').style.top = content + 'px';
}

function submit_edit_answer(content_id, uid, question_id, ans_id) {
  url = base_url + "web/submit_edit_answer.php";
  var answer = trim(document.getElementById('edit_text_answer').value);
  if (answer == '') {
    alert("Please write answer. You can not post blank answer.");
  } else {
    var param = new Array(3);
    param['answer'] = answer;
    param['content_id'] = content_id;
    param['uid'] = uid;
    var output = 'best_answer' + content_id;
    var callback_parameter = content_id + '~' + question_id + '~' + ans_id + '~' + answer;
    HTTPPost(url, param, result_submit_edit_answer, callback_parameter);
//     document.getElementById(output).innerHTML = '<div style ="float:left;text-align:center;width:100%;"><img  src="theme1/images/loading.gif" /></div>';
  }
}

function result_submit_edit_answer(data, http, content) {
  if (data) {
    document.getElementById('popup').style.display = 'none';
    var combine_id = content.split('~');
    var content_id = combine_id[0];
    var question_id = combine_id[1];
    var ans_id = combine_id[2];
    var answer = combine_id[3];
    var asker_id = document.getElementById('asker_id').value;
    var output_id = 'best_answer' + content_id;
		document.getElementById(ans_id).innerHTML = answer;
//     document.getElementById(output_id).innerHTML = '<div class="nickname_form" ><span id="name_form" style="width:100%; float:left"><b>Your Answer has been posted.Thank You.</b></span><span style = "width:100%; float:left;text-align:center;">/*<b><input type = "button" onclick = "reload_page_after_best_answer(\''+question_id+'\', \''+asker_id+'\');" value = "OK"></b>*/</span></div>';
  }
}

function select_searchresulttag(search_tags, ques_type, page) {
    get_loading_image('question');
    url = base_url + "web/ajax/search_result_tag.php?tag=" + search_tags + "&ques_type=" + ques_type + "&page=" + page;
    HTTPPost(url,'', show_searchresulttag);
}

function show_searchresulttag(data) {
  document.getElementById('question').innerHTML = data;
}

function vote_answer (question_id, poll_show, dis_type, radio_button_name) {
  var vote_type = '';
  for (var i = 0; i < document.getElementsByName(radio_button_name).length; i++) {
    if (document.getElementsByName(radio_button_name)[i].checked == true) {
      vote_type = document.getElementsByName(radio_button_name)[i].value;
    }
  }
  if (vote_type == '' && dis_type ==  'result') {
    alert('Please select any option to vote');
    return;
  } else {
    url = base_url + "web/ajax/cross_domain_ajax.php?question_id=" + question_id + "&vote_type=" + vote_type+ "&poll_show=" + poll_show;
    HTTPPost(url,'', result_vote_answer, dis_type);
  }
}

function result_vote_answer (data) {
  //window.open(base_url + "web/poll_result_on_third_party_site.php?data=" + data, null, 'scrollbars=yes ,width=400,height=400');
  //alert(data);
  document.getElementById('poll_widget').innerHTML = data;
}

function vote_answers (question_id, poll_show, dis_type, radio_button_name) {

	var vote_type = '';
	for (var i = 0; i < document.getElementsByName(radio_button_name).length; i++) {
		if (document.getElementsByName(radio_button_name)[i].checked == true) {
			vote_type = document.getElementsByName(radio_button_name)[i].value;
		}
	}
	if (vote_type == '' && dis_type ==  'result') {
		alert('Please select any option to vote');
		return;
	} else {
		url = base_url + "web/ajax/polling.php?question_id=" + question_id + "&vote_type=" + vote_type+ "&poll_show=" + poll_show;
		HTTPPost(url,'', result_vote_answers, dis_type);
		get_loading_image('poll_div');
	}
}

function result_vote_answers (data, http, dis_type) {//alert(data);
  document.getElementById('poll_div').innerHTML = data
	if(dis_type == 'result') {
		document.getElementById('res_poll_mod').style.display = 'block'
		document.getElementById('poll_mod').style.display = 'none'
	}	else {
		document.getElementById('view_result').style.display = 'block'
		document.getElementById('poll_mod').style.display = 'block'
	}
}

function change_tabs (tabs_id, number, active, show_arrow_pointer) {
  for (var inc = 1 ; inc <= number ; inc++) {
    if (inc == active) {
      document.getElementById(tabs_id + inc).className = 'active';
      document.getElementById(tabs_id + '_style' + inc).style.display = 'block';
      if (show_arrow_pointer) {
        document.getElementById(tabs_id + '_arrow' + inc).className = 'pointer_bottom';
      }
    } else {
      document.getElementById(tabs_id + inc).className = '';
      document.getElementById(tabs_id + '_style' + inc).style.display = 'none';
      if (show_arrow_pointer) {
        document.getElementById(tabs_id + '_arrow' + inc).className = 'no-bg';
      }
    }
  }
}

function show_hide_id (getaction, hidden_field, tot_tips) {
  var id = document.getElementById(hidden_field).value;
  var get_id = id.split('~');
  if (getaction == 'next') {
    if (get_id[1] == tot_tips) {
      get_id[1] = 0;
    }
    var next_id = get_id[0] + '~' + (parseInt(get_id[1]) + 1);
    var show_id = next_id;
  }
  if (getaction == 'prev') {
    if (get_id[1] == 1) {
      get_id[1] = tot_tips + 1;
    }
    var prev_id = get_id[0] + '~' + (parseInt(get_id[1]) - 1);
    var show_id = prev_id;
  }
  var temp_var = show_id;
  if (temp_var) {
    document.getElementById(show_id).style.display = 'block';
    document.getElementById(id).style.display = 'none';
    document.getElementById(hidden_field).value = temp_var;
  }

}
function chk_letusknow_form() {
	var named = document.getElementById('name').value;
	var email = document.getElementById('email').value;
	var subject = document.getElementById('sub').value;
	var mssg = document.getElementById('mssg').value;
	var captcha_text = trim(document.getElementById('captcha_text').value);
	if (named == '') {
		alert('Please enter your name');
	} else if (email == '') {
		alert('Please enter your email');
	} else 	if (subject == '') {
		alert('Please select a subject');
	} else 	if (mssg == '') {
		alert('Please enter your message');
	} else if(captcha_text == '') {
		alert('Please enter valid code.');
		return false;
	} else {
		varify_captcha('letusknow_form',captcha_text, '', '');
	}
}

function chk_contactMember_form() {
	
	var named = document.getElementById('name').value;
	var email = document.getElementById('email').value;
	var subject = document.getElementById('sub').value;
	var mssg = document.getElementById('mssg').value;
	var captcha_text = trim(document.getElementById('captcha_text').value);
	//alert('alert captcha'+captcha_text);
	if (named == '') {
		alert('Please enter your name');
	} else if (email == '') {
		alert('Please enter your email');
	} else 	if (subject == '') {
		alert('Please select a subject');
	} else 	if (mssg == '' && language_id ==1) {
		alert('Please enter your message');
	} else if(captcha_text == '') {
		alert('Please enter valid code.');
		return false;
	} else {
		//alert("before inside form");
		varify_captcha('contactMember_form',captcha_text, '', '');
	}
}

function auto_refresh_now_on_qna () {
  $.ajax({
		type: "POST",
		url: "web/ajax/now_on_qna.php",
    data: {},    //set empty data
		success: function(msg) {
			if (msg != '') {
				$('#nowonqna').html(msg);
// 			  top_events = $('#top_event').val();
			}
			setTimeout("auto_refresh_now_on_qna()",30000);
		}
	});
}

function get_loading_image(id) {
  document.getElementById(id).innerHTML = '<div style ="float:left;text-align:center;width:100%;"><img  src="' + base_url + 'theme1/images/loading.gif" /></div>';
}

// Find Position
function findPosX(obj) {
  var curleft = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  } else if (obj.x) {
    curleft += obj.x;
  }
  return curleft;
}

function findPosY(obj) {
  var curtop = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  } else if (obj.y) {
    curtop += obj.y;
  }
  return curtop;
}

function get_question_text() {
  document.getElementById('poll_widget').style.left = '5px';
  document.getElementById('get_question_text').innerHTML = document.getElementById('question_title').innerHTML;
}

function add_remove_question_to_watchlist (uid, question_id, page, action_type) {
  //get_loading_image(output_id);
  url = base_url + "web/ajax/add_remove_questions_to_watchlist.php?question_id=" + question_id + "&action_type=" + action_type + '&uid=' + uid;
  HTTPPost(url,'', result_add_remove_question_to_watchlist, page);
}

function result_add_remove_question_to_watchlist (data, http, page) {
  if (data) {
    var result = data.split('~~');
    if (page == 'permalink') {
      if (result[1] == 'add') {
        document.getElementById('watchlist_top').innerHTML = 'Question has been added to your watchlist';
        document.getElementById('watchlist_bottom').innerHTML = 'Question has been added to your watchlist';
      } else if (result[1] == 'remove') {
        document.getElementById('watchlist_top').innerHTML = 'Question has been removed from your watchlist';
        document.getElementById('watchlist_bottom').innerHTML = 'Question has been removed from your watchlist';
      }
    } else if (page == 'mypage') {
      if (result[1] == 'remove') {
        document.getElementById('watchlist').innerHTML = 'Question has been removed from your watchlist';
      }
    }
  }
}

function refresh_network_activity(uid) {
  url = base_url + "web/ajax/network_activity.php?uid=" + uid;
  HTTPPost(url,'', result_refresh_network_activity);
}

function result_refresh_network_activity (data) {
  if (data) {
    document.getElementById('networkactivity').innerHTML = data;
  }
}

function watchlist_visibility(visibile_to, uid) {
  //get_loading_image(output_id);
  url = base_url + "web/ajax/watchlist_visibility.php?visibile_to=" + visibile_to + "&uid=" + uid;
  HTTPPost(url,'', result_watchlist_visibility);
}

function result_watchlist_visibility (data) {
  if (data) {
     var val = data.split('~~');
    alert("Your WatchList will be visible to " + val[1]);
  }
}

function network_activity_report(uid) {
  $.ajax({
    type: "POST",
    url: "web/ajax/network_activity_report.php",
    success: function(msg) {
      if (msg != '') {
        window.location = base_url + "?ref=dashboard&uid=" + uid;
      }
    }
  });
}

function customize_widget(submit_id, height_id, width_id, font_id, ques_id, ans_id, bk_id, header_id, widget_code, unans_val, category_id, total, popular_val, pop_total) {
  height_size = document.getElementById(height_id).value;
  width_size = document.getElementById(width_id).value;
  font_size = document.getElementById(font_id).value;

  q_color = document.getElementById(ques_id).value;
  q_color1 = q_color.split('#');
  ques_color = q_color1[1];

  a_color = document.getElementById(ans_id).value;
  a_color1 = a_color.split('#');
  ans_color = a_color1[1];

  bk_color = document.getElementById(bk_id).value;
  bk_color1 = bk_color.split('#');
  background_color = bk_color1[1];

  h_color = document.getElementById(header_id).value;
  h_color1 = h_color.split('#');
  header_color = h_color1[1];
  if (h_color && unans_val == 'unans') {
    document.getElementById('change_tab_widget').value = h_color;
  }
  for (cnt =1; cnt <= 4; cnt++) {
    document.getElementById(submit_id+'_'+cnt).className = 'customize_widgt';
  }
  if (width_size) {
    document.getElementById(submit_id+'_3').style.width = width_size + 'px';
    document.getElementById(submit_id+'_4').style.width = width_size + 'px';
    document.getElementById('bk_'+submit_id).style.width = width_size + 'px';
    document.getElementById('height_'+submit_id).style.width = width_size + 'px';
  }
  var cnt;

  if (unans_val) {
    document.getElementById('height_'+unans_val).style.border = 'none';
    for (cnt = 1; cnt <= total; cnt++) {
      if (q_color) {
        document.getElementById('ques_'+unans_val+'_'+cnt).style.color = q_color;
      }
      if (font_size) {
        document.getElementById('font_'+unans_val+'_'+cnt).style.fontSize = font_size + 'px'
      }
      if (height_size) {
        document.getElementById('height_'+unans_val).style.height = height_size + 'px';
      }
    }
  }

  if (popular_val) {
    document.getElementById('height_'+popular_val).style.border = 'none';
    for (cnt = 1; cnt <= pop_total; cnt++) {
      if (q_color) {
      document.getElementById('ques_'+popular_val+'_'+cnt).style.color = q_color;
      }
      if (font_size) {
       document.getElementById('font_'+popular_val+'_'+cnt).style.fontSize = font_size + 'px'
      }
      if (a_color) {
        if (document.getElementById('ans_'+popular_val+'_'+cnt)) {
          document.getElementById('ans_'+popular_val+'_'+cnt).style.color = a_color;
        }
      }
      if (height_size) {
        document.getElementById('height_'+popular_val).style.height = height_size + 'px';
      }
    }
  }

  for(cnt = 1; cnt <= 5; cnt++) {
    if (q_color) {
      document.getElementById('ques_'+submit_id+'_'+cnt).style.color = q_color;
    }
    if (a_color) {
      if (document.getElementById('ans_'+submit_id+'_'+cnt)) {
        document.getElementById('ans_'+submit_id+'_'+cnt).style.color = a_color;
      }
    }
    if (font_size) {
       document.getElementById('font_'+submit_id+'_'+cnt).style.fontSize = font_size + 'px'
    }
  }
  document.getElementById('height_'+submit_id).style.border = 'none';
  if (height_size) {
    document.getElementById('height_'+submit_id).style.height = height_size + 'px';
  }
  if (h_color) {
    document.getElementById('header_'+submit_id).style.background = h_color;
  }
  if (bk_color) {
    document.getElementById('bk_'+submit_id).style.background = bk_color;
  }
//document.getElementById('width_'+submit_id).style.width = width_size + 'px';

  if (submit_id == 'featured') {
    document.getElementById(widget_code).value = "<script type='text/javascript' src='" + base_url + "index.php?ref=widget&customise=widget&subtab=featured&height=" + height_size + "&width=" + width_size + "&font=" + font_size + "&ques_color=" + ques_color + "&ans_color=" + ans_color + "&background_color=" + background_color + "&header_color=" + header_color + "'></script>";
  } else if (submit_id == 'category') {
    document.getElementById(widget_code).value = "<script type='text/javascript' src='" + base_url + "index.php?ref=widget&customise=widget&subtab=category&category_id=" + category_id + "&height=" + height_size + "&width=" + width_size + "&font=" + font_size + "&ques_color=" + ques_color + "&ans_color=" + ans_color + "&background_color=" + background_color + "&header_color=" + header_color + "'></script>";
  } else if (submit_id == 'question') {
    document.getElementById(submit_id+'_unans1').className = 'customize_widgt';
    document.getElementById(submit_id+'_unans2').className = 'customize_widgt';
    document.getElementById(submit_id+'_pop1').className = 'customize_widgt';
    document.getElementById(submit_id+'_pop2').className = 'customize_widgt';

    document.getElementById('header1_'+submit_id).style.background = 'none';
    document.getElementById('header2_'+submit_id).style.background = 'none';

    document.getElementById('header_'+submit_id).style.border = '1px solid'+h_color;
    document.getElementById('header1_'+submit_id).style.border = '1px solid'+h_color;
    document.getElementById('header2_'+submit_id).style.border = '1px solid'+h_color;

    document.getElementById(widget_code).value = "<script type='text/javascript' src='" + base_url + "index.php?ref=widget&subtab=QnA&customise=widget&height=" + height_size + "&width=" + width_size + "&font=" + font_size + "&ques_color=" + ques_color + "&ans_color=" + ans_color + "&background_color=" + background_color + "&header_color=" + header_color + "'></script>";
  }
}

function change_subcategory(val, id, page_name) {
  url = base_url + "web/ajax/change_subcategory.php?category_id=" + val + "&page_name=" + page_name;
  HTTPPost(url,'', result_change_subcategory, id);
}

function result_change_subcategory (data, http, id) {
  if (data) {
    document.getElementById(id).innerHTML = data;
  }
}

function save_expert_changes(user_id) {
  var expert_desc = document.getElementById('expert_desc').value;
  url = base_url + "web/ajax/update_expert_profile.php?user_id=" + user_id + "&expert_desc=" + expert_desc;
  HTTPPost(url,'', result_save_expert_changes);
}

function result_save_expert_changes (data) {
  if (data) {
    var str = data.split('~~');
    document.getElementById('expert_desc').value = str['0'];
    if (str['1'] == 'desc') {
    alert('Description has been updated');
    }
  }
}

function question_to_expert(asker_name, asker_email, expert_email, expert_id) {
  var ques = document.getElementById('exp_ques').value;
  var desc = document.getElementById('exp_desc').value;
  var category_id = document.getElementById('category_id').value;
  if (ques == '') {
    alert('Please ask a question.You can not post blank question.');
  } else {
    url = base_url + "web/ajax/ask_ques_expert.php";
    var param = new Array(3);
    param['ques'] = ques;
    param['desc'] = desc;
    param['asker_name'] = asker_name;
    param['asker_email'] = asker_email;
    param['expert_email'] = expert_email;
    param['category_id'] = category_id;
    param['expert_id'] = expert_id;
    HTTPPost(url,param, result_question_to_expert);
  }
}

function result_question_to_expert(data) {
  hide_div('let_us_know_module');
  alert('Question has been submitted and a mail has been sent to the Expert.');
  window.location.reload();
}

function change_expert_question_cat(action_type, cnt) {
  var question_id = Array();
  var loop;
  for (loop = 1; loop <= cnt; loop++) {
    if (document.getElementById('expert_organize'+loop).checked==true) {
      question_id = document.getElementById('expert_organize'+loop).value + ',';
    }
  }
  url = base_url + "web/ajax/update_expert_profile.php?action_type=" + action_type + "&question_id=" + question_id;
  HTTPPost(url,'', result_change_expert_question_cat);
}

function result_change_expert_question_cat(data) {
  if (data == 'error') {
    alert("Please select any question.");
  } else if (data == 'no') {
    alert("Already reported abuse.");
  } else if (data == 'report_abuse') {
    alert("Your report has been sent");
  } else {
    alert("Questions has been updated successfully");
    window.location.reload();
  }
}

// function show_my_network (data) {
//   if (data) {
//     document.getElementById('view_all_my_network').innerHTML = data;
//   }
// }

function lookup(inputString) {
  if(inputString.length == 0) { // Hide the suggestion box.
    hide_div('suggestions');
  } else {
		var params = new Array(1);
		params['queryString'] = inputString;
		url = base_url + 'web/ajax/tag_autocomplete.php';
		HTTPPost(url, params, result_lookup);
	}
}

function result_lookup(data) {//alert(data);
	if(data.length >0) {
    document.getElementById('suggestions').style.top = 505 + 'px';
		document.getElementById('suggestions').style.display = 'block';
		document.getElementById('autoSuggestionsList').innerHTML = data;
	} else {
    hide_div('suggestions');
  } 
}

function fill(tag_val) {
	document.getElementById('input_tag').value = tag_val;
  hide_div('suggestions');
}

function view_all_my_network_paging(user_id, page) {
  url = base_url + 'web/ajax/fetch_view_all_my_network.php?uid=' + user_id + "&page=" + page;
  HTTPPost(url, '', show_my_network);
}

function add_usage_report(uid, type) {
  url = base_url + 'web/ajax/add_usage_report.php?uid=' + uid + '&type=' + type;
  HTTPPost(url, '', result_add_usage_report);
}

function result_add_usage_report (data) {
}

function fetch_feature_usage_report(month, year) {
  url = base_url + 'web/ajax/feature_usage_report.php?&month=' + month + '&year=' + year;
  HTTPPost(url, '', result_fetch_feature_usage_report);
}

function result_fetch_feature_usage_report (data) {
  if (data) {
    document.getElementById('feature_usage_report').innerHTML = data;
  }
}

function blank_field() {
  document.getElementById('exp_ques').value = '';
  document.getElementById('exp_desc').value = '';
}

function show_panel(uid) {
  if(uid == 0) {
    display_sign_in_box('exp');
    display_div('asd');
    return false;
  } else {
    display_div('ask_ques_form');
    hide_div('home_quest');
  }
}

/* added by nitin */





function LiveStream(textdiv, questionsarray, bar_wid) {
  ClockID = 0;
  timer = 0;
  typeInterval = 66;
  questionInterval = 10000;

  textDiv = textdiv;
  questionsArray = questionsarray;
  questionIndex = -1;

  typeString = null;
  typePos = 0;
  str_length = 0;
  bar_wid = bar_wid;

  if(questionsArray != null) {
    typeit();
  }
}

function typeit() {
  clearTimeout(timer);
  var leng = questionsArray.length;

  questionIndex++;
  questionIndex = questionIndex%leng;

  typeString = questionsArray[questionIndex].question;
  if (typeString.length > 12 && document.getElementById('bar_head').value == 'tag') {
    str_length = 12;
  } else if(typeString.length > 7 && document.getElementById('bar_head').value == 'letusknow') {
    str_length = 7;
  } else if(typeString.length > 70) {
    str_length = 70;
  } else {
    str_length = typeString.length;
  }
  typePos = 0;
  var disp_obj = document.getElementById(textDiv);
  disp_obj.innerHTML = '';
  
  
  ClockID = setInterval(function(){typeit_interval();}, typeInterval);
}

function typeit_interval() {
  var disp_obj = document.getElementById(textDiv);
  //document.getElementById('user').innerHTML = '<b>' + questionsArray[questionIndex].user + '</b>';
  if(typePos <= str_length) {
    var stemp = typeString.substr(typePos, 1);
    if(typePos == str_length && str_length > 12) {
      clearInterval(ClockID);
      stemp += ' - <a href=' + questionsArray[questionIndex].q_link + '><img src="' + base_url + 'theme1/images/ticker_answernow.jpg" border="0" align="absmiddle" /></a>';

      timer = setTimeout(function(){typeit();}, questionInterval);
    } else if(typePos == str_length && str_length <= 12) {
      clearInterval(ClockID);
      stemp += '... - <a href=' + questionsArray[questionIndex].q_link + '><img src="' + base_url + 'theme1/images/ticker_answernow.jpg" border="0" align="absmiddle" /></a>';

      timer = setTimeout(function(){typeit();}, questionInterval);
    } else {
      typePos++;
      stemp += '_';
    }
    disp_obj.innerHTML = disp_obj.innerHTML.substr(0, disp_obj.innerHTML.length-1);
    disp_obj.innerHTML += stemp;
  }
}
// nitin form 

var divIdArray=['parent_cat','sub_category','tag_category','tag_category2','tag_category3','tag_category4','tag_category5','statelist','preview'];
var current_id = '';
function hideShowDiv(currentDiv){ 
	var cnt = 0;
	var flag = false;
	//alert("current div wtih '' "+currentDiv);
	currentDiv = currentDiv;
	//currentDiv = currentDiv;
	for(var i = 0 ; i < divIdArray.length ; i++ ){
		var divIDToRemove = divIdArray[i];
		//alert(currentDiv+"  =  "+divIDToRemove);
		if(flag == true){
			 if(document.getElementById(divIDToRemove) != null){
				if(cnt != 0 ){
					document.getElementById(divIDToRemove).style.display = 'none';						
				}
				else{
					document.getElementById(divIDToRemove).style.display = 'block';
					cnt++;
				}
			 }
		}
		if(currentDiv == divIDToRemove){
			flag = true;
			//$('parent_'+divIDToRemove).style.display = 'none';
		}
	}
}






//COMMENTED BY PRALHAD

/*
function change_subcat_toi(id,sel,is_admin)
{
	
  url = base_url + "web/ajax/fetch_subcat_toi.php?catid="+id+"&sel="+sel+"&is_admin="+is_admin;
  HTTPPost(url,'', show_subcat_toi, 0);
}

function show_subcat_toi(data) { 
  document.getElementById('sub_category').innerHTML= data;
}

function change_subtag(id,sel,is_admin,tag_level) {
 url = base_url + "web/ajax/fetch_taglist.php?catid="+id+"&sel="+sel+"&is_admin="+is_admin+"&tag_level="+tag_level;
  HTTPPost(url,'', show_tag, 0);
}

function show_tag(data) { 
if(data=='yes'){
 showPopupDiv('favArea');
 document.getElementById('tag_category').style.display = 'none';
}else if(data=='priveiw'){ 
document.getElementById('preview').style.display = 'block';
document.getElementById('tag_category').style.display = 'none';

}
else{
  document.getElementById('tag_category').innerHTML= data;
}
}

function change_subtag2(id,sel,is_admin,tag_level) { 
  url = base_url + "web/ajax/fetch_taglist2.php?catid="+id+"&sel="+sel+"&is_admin="+is_admin+"&tag_level="+tag_level;
  
  HTTPPost(url,'', show_tag2, 0);
}

function show_tag2(data) { //alert("data is2"+data);
 if(data=='yes'){
 showPopupDiv('favArea');
 document.getElementById('tag_category2').style.display = 'none';
}else if(data=='priveiw'){ 
document.getElementById('preview').style.display = 'block';
document.getElementById('tag_category2').style.display = 'none';

}
else{
  document.getElementById('tag_category2').innerHTML= data;
}
}


function change_subtag3(id,sel,is_admin,tag_level) { 
  url = base_url + "web/ajax/fetch_taglist3.php?catid="+id+"&sel="+sel+"&is_admin="+is_admin+"&tag_level="+tag_level;
  HTTPPost(url,'', show_tag3, 0);
}

function show_tag3(data) { 
	if(data=='yes'){
		showPopupDiv('favArea');
		document.getElementById('tag_category3').style.display = 'none';
	}else if(data=='priveiw'){ 
	document.getElementById('preview').style.display = 'block';
	document.getElementById('tag_category3').style.display = 'none';
	}
	else{
	  document.getElementById('tag_category3').innerHTML= data;
	}	
}

function change_subtag4(id,sel,is_admin,tag_level) { 
  url = base_url + "web/ajax/fetch_taglist4.php?catid="+id+"&sel="+sel+"&is_admin="+is_admin+"&tag_level="+tag_level;
  HTTPPost(url,'', show_tag4, 0);
}

function show_tag4(data) { 
	if(data=='yes'){
		showPopupDiv('favArea');
		document.getElementById('tag_category4').style.display = 'none';
	}else if(data=='priveiw'){ 
		document.getElementById('preview').style.display = 'block';
		document.getElementById('tag_category4').style.display = 'none';
	}
	else{
		document.getElementById('tag_category4').innerHTML= data;
	}
}


function change_subtag5(id,sel,is_admin,tag_level) { 
  url = base_url + "web/ajax/fetch_taglist5.php?catid="+id+"&sel="+sel+"&is_admin="+is_admin+"&tag_level="+tag_level;
  HTTPPost(url,'', show_tag5, 0);
}

function show_tag5(data) {if(data=='yes'){
 showPopupDiv('favArea');
 document.getElementById('tag_category5').style.display = 'none';
}else if(data=='priveiw'){ 
document.getElementById('preview').style.display = 'block';
document.getElementById('tag_category5').style.display = 'none';
}
else{
  document.getElementById('tag_category5').innerHTML= data;
}
}

function show_state(id,sel,is_admin,tag_level,div_id) { //alert("id..."+id);
  url = base_url + "web/ajax/fetch_statelist.php?catid="+id+"&sel="+sel+"&is_admin="+is_admin+"&tag_level="+tag_level;
  HTTPPost(url,'', show_statelist, 0);
  hidePopupDiv(div_id)
}

function show_statelist(data) { //alert(data);
document.getElementById('statelist').style.display = 'block';
document.getElementById('preview').style.display = 'block';
  document.getElementById('statelist').innerHTML= data;
}

*/

function wait(msecs)
{
var start = new Date().getTime();
var cur = start
while(cur - start < msecs)
{
cur = new Date().getTime();
} 
} 

 function tagsappend(frm){
		var myselectedtext="";
		var selected_index;
		var selected_text; 
		
		if(document.getElementById('first_level_tag') !=  null){
			 selected_index = document.getElementById('first_level_tag').selectedIndex;
   			 selected_text = document.getElementById('first_level_tag').options[selected_index].text;
			 myselectedtext = selected_text;
			 
		}
		
		if(document.getElementById('second_level_tag') !=  null){
			 selected_index = document.getElementById('second_level_tag').selectedIndex;
   			 selected_text = document.getElementById('second_level_tag').options[selected_index].text;
			 myselectedtext = myselectedtext +","+selected_text;
		}
		
		if(document.getElementById('third_level_tag') !=  null){
			 selected_index = document.getElementById('third_level_tag').selectedIndex;
   			 selected_text = document.getElementById('third_level_tag').options[selected_index].text;
			 myselectedtext = myselectedtext +","+selected_text;
		}
		
		if(document.getElementById('four_level_tag') !=  null){
			 selected_index = document.getElementById('four_level_tag').selectedIndex;
   			 selected_text = document.getElementById('four_level_tag').options[selected_index].text;
			 myselectedtext = myselectedtext +","+selected_text;
		}
		
		if(document.getElementById('five_level_tag') !=  null){
			 selected_index = document.getElementById('five_level_tag').selectedIndex;
   			 selected_text = document.getElementById('five_level_tag').options[selected_index].text;
			 myselectedtext = myselectedtext +","+selected_text;
		}
		
		if(document.getElementById('custom_tag').value){
   			 selected_text = document.getElementById('custom_tag').value;
			 myselectedtext = myselectedtext +","+selected_text;
		}
		//alert(myselectedtext);
		document.getElementById('input_tag').value = myselectedtext;
		
		
	/*	var ee;	

	//First Level Tag
	if(document.Question.first_level_tag!= null){			
		var w = document.Question.first_level_tag.selectedIndex;
			if(document.Question.first_level_tag.options[document.Question.first_level_tag.selectedIndex].value != null){
				var bb = document.Question.first_level_tag.options[document.Question.first_level_tag.selectedIndex].value;
				myselectedtext = document.Question.first_level_tag.options[w].text;

			document.Question.first_level.value = bb ;
		}
	}
	//Second Level Tag

			if(document.Question.second_level_tag!= null){
			
				var p = document.Question.second_level_tag.selectedIndex;
				
				if(document.Question.second_level_tag.options[document.Question.second_level_tag.selectedIndex].value != null){
					var cc = document.Question.second_level_tag.options[document.Question.second_level_tag.selectedIndex].value;
					myselectedtext = myselectedtext +","+ document.Question.second_level_tag.options[p].text;
					document.Question.second_level.value = cc ; 
				 }
			}

	//Third Level Tag
		if(document.Question.third_level_tag!= null){
		var q = document.Question.third_level_tag.selectedIndex;
		if(document.Question.third_level_tag.options[document.Question.third_level_tag.selectedIndex].value != null){
			var dd = document.Question.third_level_tag.options[document.Question.third_level_tag.selectedIndex].value;
			myselectedtext = myselectedtext +","+document.Question.third_level_tag.options[q].text;
			document.Question.third_level.value = dd ;
		}
		}
	//Four Level Tag
		if(document.Question.four_level_tag!= null){
		var r = document.Question.four_level_tag.selectedIndex;
		if(document.Question.four_level_tag.options[document.Question.four_level_tag.selectedIndex].value != null){
			var ff = document.Question.four_level_tag.options[document.Question.four_level_tag.selectedIndex].value;
			myselectedtext = myselectedtext +","+document.Question.four_level_tag.options[r].text;
			document.Question.four_level.value = ff; 
		}
	}
	//Five Level Tag
		if(document.Question.five_level_tag!= null){
		var s = document.Question.five_level_tag.selectedIndex;
		if(document.Question.five_level_tag.options[document.Question.five_level_tag.selectedIndex].value != null){
			var ee = document.Question.five_level_tag.options[document.Question.five_level_tag.selectedIndex].value;
			 myselectedtext = myselectedtext +","+document.Question.five_level_tag.options[s].text;
			document.Question.five_level.value = ee ; 
			}
		}

	// State List
		if(document.Question.statelist!= null){
		var statelist = document.Question.statelist.selectedIndex;
		if(document.Question.statelist.options[document.Question.statelist.selectedIndex].value != null){
			var ss = document.Question.statelist.options[document.Question.statelist.selectedIndex].value;
		myselectedtext = myselectedtext +","+document.Question.statelist.options[statelist].text;
		}
	}
		document.Question.q_tags.value=myselectedtext;*/
		return true;
	}

	function showPopupDiv(divid) { 
			var Element = document.getElementById(divid); 
			//objh = parseFloat(Element.style.height)/2; 
			//objw = parseFloat(Element.style.width)/2; 
			objh = 200; 
			objw = 200; 
			Element.style.display = 'block';
			Element.style.top = Math.floor(Math.round((document.documentElement.offsetHeight/2)+document.documentElement.scrollTop)-objh)+'px'; 
			Element.style.left = Math.floor(Math.round((document.documentElement.offsetWidth/2)+document.documentElement.scrollLeft)-objw)+'px';
	}
	function hidePopupDiv(divId)
	{
		var Element = document.getElementById(divId);
		Element.style.display = "none";
	}

//PRLAHAD code start for Category list
		
function change_subcategorylist(id,level){ 
	url = base_url + "web/ajax/fetch_tagcategory_result.php?catid="+id+"&level="+level;
	HTTPPost(url,'', show_sub_cat, 0);
}


//FOR CITY LIST
function check_citylist(id, level, NoRegionLevel, sequence){
	document.getElementById('selectedtag').value = id;
	document.getElementById('NoRegionLevel').value = NoRegionLevel;
	document.getElementById('level').value = level;
	document.getElementById('currentlevel').value = level;
	document.getElementById('sequence').value = sequence;
	url = base_url + "web/ajax/fetch_tagcategory_result.php?catid="+id+"&level="+level+"&check=C";
	HTTPPost(url,'', show_citylist, 0);
}

function allowlist(){
	var newLevel = document.getElementById('level').value;
	switch(newLevel){
		case '1':
			document.getElementById('tag_category').style.display = 'block';
		break;
		case '2':
			document.getElementById('tag_category2').style.display = 'block';
		break;
		case '3':
			document.getElementById('tag_category3').style.display = 'block';
		break;
		case '4':
			document.getElementById('tag_category4').style.display = 'block';
		break;
		case '5':
			document.getElementById('preview').style.display = 'block';
		break;
	}
	if(document.getElementById('region').value == 'state')
	hidePopupDiv('stateArea');
	if(document.getElementById('region').value == 'city')
	hidePopupDiv('cityArea');
}

function disallowlist(){
	var citylevel = document.getElementById('level').value;
	document.getElementById('preview').style.display = 'block';
	if(document.getElementById('region').value == 'state')
	hidePopupDiv('stateArea');
	if(document.getElementById('region').value == 'city')
	hidePopupDiv('cityArea');
}

function show_citylist(data) {
	var newurl;
	var level = document.getElementById('level').value;
	var NoRegionLevel = document.getElementById('NoRegionLevel').value;
	var selectedtag = document.getElementById('selectedtag').value;
	var sequence = document.getElementById('sequence').value;
	var currentlevel = document.getElementById('currentlevel').value;
	
	if(data){
		//if(confirm('Is this question related to a city?')){
		document.getElementById('region').value = 'city';
		showPopupDiv('cityArea');
		newurl = base_url + "web/ajax/fetch_tagcategory_result.php?catid="+selectedtag+'&level='+level+'&city=1&sequence='+sequence+'&currentlevel='+currentlevel;
		//}
	}
	else {
		check_statelist(selectedtag, level, NoRegionLevel, sequence);
	}
	switch(level){
		case '1':
			HTTPPost(newurl,'', show_taglist, 0);
		break;
		case '2':
			HTTPPost(newurl,'', show_taglist2, 0);
		break;
		case '3':
			HTTPPost(newurl,'', show_taglist3, 0);
		break;
		case '4':
			HTTPPost(newurl,'', show_taglist4, 0);
		break;
		case '5':
			HTTPPost(newurl,'', show_taglist5, 0);
		break;
	}	
}

//FOR STATE LIST
function check_statelist(id, level, StateLevel, sequence){ //alert('checking statelist');
	document.getElementById('selectedtag').value = id;
	document.getElementById('NoStateLevel').value = StateLevel;
	document.getElementById('level').value = level;
	document.getElementById('currentlevel').value = level;
	document.getElementById('sequence').value = sequence;
	url = base_url + "web/ajax/fetch_tagcategory_result.php?catid="+id+"&level="+level+"&check=S";
	HTTPPost(url,'', show_statelist, 0);
}
function show_statelist(data) {
	var newurl;
	var level = document.getElementById('level').value;
	var NoStateLevel = document.getElementById('NoStateLevel').value;
	var selectedtag = document.getElementById('selectedtag').value;
	var sequence = document.getElementById('sequence').value;
	var currentlevel = document.getElementById('currentlevel').value;
	
	if(data) {
		//if(confirm('Is this question related to a state?')){
		document.getElementById('region').value = 'state';	
		showPopupDiv('stateArea');	
		newurl = base_url + "web/ajax/fetch_tagcategory_result.php?catid="+selectedtag+'&level='+level+'&state=1&sequence='+sequence+'&currentlevel='+currentlevel+'&allow=1';
		//}
	} else{	
		newurl = base_url + "web/ajax/fetch_tagcategory_result.php?catid="+selectedtag+'&currentlevel='+currentlevel+'&state=0&sequence='+sequence+'&level='+NoStateLevel;
	}
	
	switch(level){
		case '1':
			HTTPPost(newurl,'', show_taglist, 0);
		break;
		case '2':
			HTTPPost(newurl,'', show_taglist2, 0);
		break;
		case '3':
			HTTPPost(newurl,'', show_taglist3, 0);
		break;
		case '4':
			HTTPPost(newurl,'', show_taglist4, 0);
		break;
		case '5':
			HTTPPost(newurl,'', show_taglist5, 0);
		break;
	}	
}

function change_list(id,level,NoRegionLevel,NoStateLevel,sequence){	
	document.getElementById('sequence').value = sequence;
	document.getElementById('selectedtag').value = id;
	document.getElementById('NoRegionLevel').value = NoRegionLevel;
	document.getElementById('NoStateLevel').value = NoStateLevel;
	document.getElementById('level').value = level;
	document.getElementById('currentlevel').value = level;
	document.getElementById('region').value = '';
	//alert(document.getElementById('region').value);
	url = base_url + "web/ajax/fetch_tagcategory_result.php?catid="+id+"&level="+level+"&sequence="+sequence+"&currentlevel="+level;
	switch(level){
		case 0:
			HTTPPost(url,'', show_sub_cat, 0);
		break;
		case 1:
			if(NoRegionLevel == 5) check_citylist(id, level, NoRegionLevel, sequence);	
			else if(NoStateLevel == 6) check_statelist(id, level, NoStateLevel, sequence);
			else HTTPPost(url,'', show_taglist, 0);
		break;
		case 2:
			if(NoRegionLevel == 5) check_citylist(id, level, NoRegionLevel, sequence);	
			else if(NoStateLevel == 6) check_statelist(id, level, NoStateLevel, sequence);
			else HTTPPost(url,'', show_taglist2, 0);
		break;
		case 3:
			if(NoRegionLevel == 5) check_citylist(id, level, NoRegionLevel, sequence);
			else if(NoStateLevel == 6) check_statelist(id, level, NoStateLevel, sequence);
			else HTTPPost(url,'', show_taglist3, 0);
		break;
		case 4:
			if(NoRegionLevel == 5) check_citylist(id, level, NoRegionLevel, sequence);	
			else if(NoStateLevel == 6) check_statelist(id, level, NoStateLevel, sequence);
			else HTTPPost(url,'', show_taglist4, 0);
		break;
		case 5: 
			if(NoRegionLevel == 5) check_citylist(id, level, NoRegionLevel, sequence);	
			else if(NoStateLevel == 6) check_statelist(id, level, NoStateLevel, sequence);
			else HTTPPost(url,'', show_taglist6, 0);
		break;
	}
}

function show_sub_cat(data) { 
  	if(data){
		document.getElementById('left_subcat_col').style.display = 'block';
		document.getElementById('right_subcat_col').style.display = 'block';
		document.getElementById('sub_category').innerHTML= data;
		if(document.getElementById('region').value == 'city' || document.getElementById('region').value == 'state')
		document.getElementById('sub_category').style.display = 'none';
		else document.getElementById('sub_category').style.display = 'block';
		document.getElementById('tag_category').style.display = 'none';
		document.getElementById('tag_category2').style.display = 'none';
		document.getElementById('tag_category3').style.display = 'none';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
	else{
		document.getElementById('left_subcat_col').style.display = 'none';
		document.getElementById('right_subcat_col').style.display = 'none';
		document.getElementById('preview').style.display = 'block';
		document.getElementById('sub_category').style.display = 'none';	
		document.getElementById('tag_category').style.display = 'none';
		document.getElementById('tag_category2').style.display = 'none';
		document.getElementById('tag_category3').style.display = 'none';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
}

function show_taglist(data) { 
  	if(data){
		document.getElementById('tag_category').innerHTML= data;
		if(document.getElementById('region').value == 'city' || document.getElementById('region').value == 'state')
		document.getElementById('tag_category').style.display = 'none';
		else document.getElementById('tag_category').style.display = 'block';
		document.getElementById('preview').style.display = 'none';
		document.getElementById('tag_category2').style.display = 'none';
		document.getElementById('tag_category3').style.display = 'none';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
	else{
		document.getElementById('preview').style.display = 'block';
		document.getElementById('tag_category').style.display = 'none';
		document.getElementById('tag_category2').style.display = 'none';
		document.getElementById('tag_category3').style.display = 'none';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
}

function show_taglist2(data) { 
  	if(data){
		document.getElementById('tag_category2').innerHTML= data;
		if(document.getElementById('region').value == 'city' || document.getElementById('region').value == 'state')
		document.getElementById('tag_category2').style.display = 'none';
		else document.getElementById('tag_category2').style.display = 'block';
		document.getElementById('preview').style.display = 'none';
		document.getElementById('tag_category3').style.display = 'none';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
	else{
		document.getElementById('preview').style.display = 'block';
		document.getElementById('tag_category2').style.display = 'none';
		document.getElementById('tag_category3').style.display = 'none';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
}

function show_taglist3(data) { 
  	if(data){
		document.getElementById('tag_category3').innerHTML= data;
		if(document.getElementById('region').value == 'city' || document.getElementById('region').value == 'state')
		document.getElementById('tag_category3').style.display = 'none';
		else document.getElementById('tag_category3').style.display = 'block';
		document.getElementById('preview').style.display = 'none';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
	else{
		document.getElementById('preview').style.display = 'block';
		document.getElementById('tag_category3').style.display = 'none';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
}

function show_taglist4(data) { 
  	if(data){
		document.getElementById('preview').style.display = 'none';
		if(document.getElementById('region').value == 'city' || document.getElementById('region').value == 'state')
		document.getElementById('tag_category4').style.display = 'none';
		else document.getElementById('tag_category4').style.display = 'block';
		document.getElementById('tag_category4').innerHTML= data;
		document.getElementById('tag_category5').style.display = 'none';
	}
	else{
		document.getElementById('preview').style.display = 'block';
		document.getElementById('tag_category4').style.display = 'none';
		document.getElementById('tag_category5').style.display = 'none';
	}
}

function show_taglist5(data) { 
  	if(data){
		document.getElementById('preview').style.display = 'none';
		if(document.getElementById('region').value == 'city' || document.getElementById('region').value == 'state')
		document.getElementById('tag_category5').style.display = 'none';
		else document.getElementById('tag_category5').style.display = 'block';
		document.getElementById('tag_category5').innerHTML= data;
	}
	else{
		document.getElementById('preview').style.display = 'block';
		document.getElementById('tag_category5').style.display = 'none';
	}
}

//To show citylist
function show_taglist6(data) { 
  	if(data){
		document.getElementById('preview').style.display = 'none';
		document.getElementById('tag_category6').style.display = 'block';
		document.getElementById('tag_category6').innerHTML= data;
	}
	else{
		document.getElementById('preview').style.display = 'block';
		document.getElementById('tag_category6').style.display = 'none';
	}
}

//end of PRALHAD code

//PRALHAD code start for editor3
function HyperTextArea(name, html, width, height,resourcePath,styleSheetUrl,delayRender){
	this.isRichText = false;
	this.rng = null;

	this.name = name;
	this.html = html||"";
	this.width = width;
	this.height = height;
	this.resourcePath = resourcePath||"";
	this.styleSheetUrl = styleSheetUrl||null;
	if(this.resourcePath.length && this.resourcePath.substring(this.resourcePath.length-1) != "/"){
		this.resourcePath = this.resourcePath + "/";
	}
	this.delayRender = delayRender||false;
	this.controlNames = new Array();
	this.controlsByName = new Array();
	this.toolbarNames = new Array();
	this.designModeRetryCount = 0;
	this.isSrcView = false;

	this.init = function(){
		HyperTextArea.areas[this.name] = this;
		//check to see if designMode mode is available
		if (document.getElementById) {
			if (document.all) {
				//check for Internet Explorer 5+
				this.isRichText = true;
			} else {
				//check for browsers that support designmode
				//make sure that this is not safari (and perhaps other khtml based browsers) which returns "inherit" for document.designMode 
				if (document.designMode && document.designMode.toLowerCase() != "inherit"){
					this.isRichText = true;
				}
			}
		}

		this.addControl(new Toolbar("toolbar0"));
		//menus
		styleMenu = new Menu("formatblock","formatblock");
		styleMenu.addItems("","Style","<p>","Paragraph","<h1>","Heading 1","<h2>","Heading 2","<h3>","Heading 3","<h4>","Heading 4","<h5>","Heading 5","<h6>","Heading 6","<address>","Address","<pre>","Preformatted");
		this.addControl(styleMenu);
		fontMenu = new Menu("fontname","fontname");
		fontMenu.addItems("","Font","Arial, Helvetica, sans-serif","Arial","Courier New, Courier, mono","Courier New","Times New Roman, Times, serif","Times New Roman","Verdana, Arial, Helvetica, sans-serif","Verdana");
		this.addControl(fontMenu);
		sizeMenu = new Menu("fontsize","fontsize");
		sizeMenu.addItems("","Size",1,1,2,2,3,3,4,4,5,5,6,6,7,7);
		this.addControl(sizeMenu);
	
		this.addControl(new Toolbar("toolbar1"));

		//add default controls
		this.addControl(new TextFormatButton("bold","Bold","images/post_button_bold.gif","bold"));
		this.addControl(new TextFormatButton("italic","Italic","images/post_button_italic.gif","italic"));
		this.addControl(new Spacer());
		this.addControl(new TextFormatButton("left","Align Left","images/post_button_left_just.gif","justifyleft"));
		this.addControl(new TextFormatButton("center","Center","images/post_button_centre.gif","justifycenter"));
		this.addControl(new TextFormatButton("right","Align Right","images/post_button_right_just.gif","justifyright"));
		this.addControl(new Spacer());
		this.addControl(new TextFormatButton("orderedlist","Ordered List","images/post_button_numbered_list.gif","insertorderedlist"));
		this.addControl(new TextFormatButton("unorderedlist","Unordered List","images/post_button_list.gif","insertunorderedlist"));
		this.addControl(new Spacer());
		this.addControl(new TextFormatButton("outdent","Outdent","images/post_button_outdent.gif","outdent"));
		this.addControl(new TextFormatButton("indent","Indent","images/post_button_indent.gif","indent"));
		this.addControl(new TextFormatButton("forecolor","Text Color","images/post_button_textcolor.gif","forecolor"));
		this.addControl(new TextFormatButton("hilitecolor","Background Color","images/post_button_bgcolor.gif","hilitecolor"));
		this.addControl(new Spacer());
		this.addControl(new Button("insertImage","images/post_button_image.gif","Insert Image","addImage"));
		this.addControl(new TextFormatButton("link","Create Link","images/post_button_hyperlink.gif","createlink"));
		this.addControl(new Button("insertTable","images/post_button_table.gif","Insert Table","insertTableDialog"));
		
	}
	
	this.addControl = function(control){
		control.resourcePath = this.resourcePath;
		control.area = this;
		i = this.controlNames.length
		this.controlNames[eval(i)] = control.name;
		this.controlsByName[control.name] = control;
	}
	
	this.getControl = function(name){
		return this.controlsByName[name];
	}
	
	this.replaceControl = function(oldName,newControl){
		if(this.getControl(oldName)){
			for(i=0;i<this.controlNames.length;i++){
				if(this.controlNames[i] == oldName){
					break;
				}
			}
		}else{
			i = this.controlNames.length;
		}
		newControl.area = this;
		newControl.resourcePath = this.resourcePath;
		this.controlNames[i] = newControl.name;
		this.controlsByName[newControl.name] = newControl;
	}
	
	this.insertControl = function(i,control){
		control.resourcePath = this.resourcePath;
		control.area = this;
		this.controlNames.splice(i,0, control.name);
		this.controlsByName[control.name] = control;
	}
	
	this.removeControl = function(name){
		for(i=0;i<this.controlNames.length;i++){
			if(this.controlNames[i] == name){
				this.controlNames.splice(i,1);
				return true;
			}
		}
		return false;
	}

	this.render = function(html){
		HyperTextArea.activeArea = this;
		text="this.render\n\n";
		for(i=0;i<this.controlNames.length;i++){
			text = text + "\t" + this.controlNames[i] + "\n";
		}
		if (this.isRichText) {
			this._renderRTE(html);
		} else {
			this._renderDefault(html);
		}
	}

	this._renderDefault = function(html){
		document.writeln('<textarea name="' + this.name + '" id="' + this.name + '" style="width: ' + this.width + 'px; height: ' + this.height + 'px;">' + html + '</textarea>');
	}

	this.getControlNames = function(lable){
		text= lable + "\n\n";
		for(i=0;i<this.controlNames.length;i++){
			text = text + "\t" + this.controlNames[i] + "\n";
		}
		return text;
		
	}
	
	this._renderControls = function(){
		text = "";
		for(x=0;x<this.controlNames.length;x++){
			control = this.controlsByName[this.controlNames[x]];
			if(control){
				text = text + control.getRenderedText();
			}
		}	
		text = text + '</tr>';
		text = text + '</table>';
		document.writeln(text);
	}
	
	this._renderRTE = function(){
		document.writeln('<style type="text/css">');
		document.writeln('.btnImage {cursor: pointer; cursor: hand;}');
		document.writeln('</style>');

		this._renderControls();
		document.writeln('<iframe id="' + this.name + '" width="' + this.width + 'px" height="' + this.height + 'px"></iframe>');
		document.writeln('<br /><input type="checkbox" id="chkSrc' + this.name + '" onclick="HyperTextArea.getArea(\''+this.name+'\').toggleHTMLSrc();" />&nbsp;View Source');
		//reimplement this so that it is not in an iframe, rather in a div.
		document.writeln('<iframe width="145" height="130" id="cp' + this.name + '" name="cp' + this.name + '" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; position: absolute;"></iframe>');
		document.writeln('<input type="hidden" id="hdn' + this.name + '" name="' + this.name + '" value="">');
		document.getElementById('hdn' + this.name).value = this.html;
		this.initializeContent(this.html);
		setTimeout('onHyperTextAreaLoad(\'' + this.name + '\')', 500);
	}

	this.initializeContent = function(html){
		HyperTextArea.activeArea = this;
		var frameHtml = "<html>\n";
		frameHtml += "<head>\n";
		if (this.styleSheetUrl){
			frameHtml += "<link media=\"all\" type=\"text/css\" href=\"" + this.styleSheetUrl + "\" rel=\"stylesheet\">\n";
		}
		frameHtml += "</head>\n";
		frameHtml += "<body>\n";
		frameHtml += html;
		frameHtml += "</body>\n";
		frameHtml += "</html>";
		
		if (document.all) {
			var oRTE = frames[this.name].document;
			oRTE.open();
			oRTE.write(frameHtml);
			oRTE.close();
		} else {
			var oRTE = document.getElementById(this.name).contentWindow.document;
			oRTE.open();
			oRTE.write(frameHtml);
			oRTE.close();
			//attach a keyboard handler for Mozilla to make keyboard shortcuts for formatting text work
			oRTE.addEventListener("keypress", kb_handler, true);
		}
	}

	this.setContent = function(html){
		HyperTextArea.activeArea = this;
		var oRTE;
		if (document.all) {
			oRTE = frames[this.name].document;
		} else {
			oRTE = document.getElementById(this.name).contentWindow.document;
		}
		body = oRTE.getElementsByTagName("body");
		body.innerHTML = html;
	}

	this.update = function(){
		this.setViewMode(false);

		//set message value
		var oHdnMessage = document.getElementById('hdn' + this.name);
		var oRTE = document.getElementById(this.name);
		
		if (this.isRichText) {
			if (oHdnMessage.value == null) oHdnMessage.value = "";
			if (document.all) {
				oHdnMessage.value = frames[this.name].document.body.innerHTML;
			} else {
				oHdnMessage.value = oRTE.contentWindow.document.body.innerHTML;
			}
			//if there is no content (other than formatting) set value to nothing
			if (stripHTML(oHdnMessage.value.replace("&nbsp;", " ")) == "") oHdnMessage.value = "";
			this.html = oHdnMessage.value;
		}
	}

	this.setToolbarsVisible = function(isVisible){
			visibleStyle = isVisible?"visible":"hidden";
			for (x=0;x<this.toolbarNames.length;x++){
				document.getElementById(this.toolbarNames[x] + "_" + this.name).style.visibility = visibleStyle;
			}
	}

	this.setViewMode = function(isSrcView){
		HyperTextArea.activeArea = this;
		//contributed by Bob Hutzel (thanks Bob!)
		var oRTE;
		if (document.all) {
			oRTE = frames[this.name].document;
		} else {
			oRTE = document.getElementById(this.name).contentWindow.document;
		}
		
		//only change the view if it is different than the current state
		if (isSrcView && !this.isSrcView){
			this.isSrcView = true;
			this.setToolbarsVisible(false);
			if (document.all) {
				oRTE.body.innerText = oRTE.body.innerHTML;
			} else {
				var htmlSrc = oRTE.createTextNode(oRTE.body.innerHTML);
				oRTE.body.innerHTML = "";
				oRTE.body.appendChild(htmlSrc);
			}
		}else if(!isSrcView && this.isSrcView){
			this.isSrcView = false;
			this.setToolbarsVisible(true);
			if (document.all) {
				oRTE.body.innerHTML = oRTE.body.innerText;
			} else {
				var htmlSrc = oRTE.body.ownerDocument.createRange();
				htmlSrc.selectNodeContents(oRTE.body);
				oRTE.body.innerHTML = htmlSrc.toString();
			}
		}
		
	}
	
	this.toggleHTMLSrc = function(){
		if (document.getElementById("chkSrc" + this.name).checked) {
			this.setViewMode(true);
		} else {
			this.setViewMode(false);
		}
	}

	//TODO would really like to be able to plug functionality in here.  This would include the ability to launch a wizard, and then insert arbitrary text at the insertion point
	this.formatText = function (command,option){
		HyperTextArea.activeArea = this;
		var oRTE;
		if (document.all) {
			oRTE = frames[this.name];
		} else {
			oRTE = document.getElementById(this.name).contentWindow;
		}
		
		if ((command == "forecolor") || (command == "hilitecolor")) {
			this.command = command;
			controlElement = document.getElementById(this.name +"_" + command);
			cp = document.getElementById('cp' + this.name);
			this.cpWindow.area = this;
			cp.style.left = getOffsetLeft(controlElement) + "px";
			cp.style.top = (getOffsetTop(controlElement) + controlElement.offsetHeight) + "px";
			if (cp.style.visibility == "hidden") {
				cp.style.visibility="visible";
			} else {
				cp.style.visibility="hidden";
			}
			
			//get current selected range
			var sel = oRTE.document.selection; 
			if (sel != null) {
				this.rng = sel.createRange();
			}
		} else if (command == "createlink") {
			//TODO need a way to make tihs more flixible.  Would especially like to be able to insert a link with both the containing text and the URL
			var szURL = prompt("Enter a URL:", "");
			oRTE.document.execCommand("Unlink",false,null)
			oRTE.document.execCommand("CreateLink",false,szURL)
		} else {
			oRTE.focus();
		  	oRTE.document.execCommand(command, false, option);
			oRTE.focus();
		}

	}

	this.setColor = function(color){
		HyperTextArea.activeArea = this;
		
		var oRTE;
		if (document.all) {
			oRTE = frames[this.name];
		} else {
			oRTE = document.getElementById(this.name).contentWindow;
		}
		
		//var parentCommand = parent.command;
		if (document.all) {
			//retrieve selected range
			var sel = oRTE.document.selection; 
			if (this.command == "hilitecolor") this.command = "backcolor";
			if (sel != null) {
				var newRng = sel.createRange();
				newRng = this.rng;
				newRng.select();
			}
		} else {
			oRTE.focus();
		}
		oRTE.document.execCommand(this.command, false, color);
		oRTE.focus();
		document.getElementById('cp' + this.name).style.visibility = "hidden";
	}
	
	this.addImage = function(imagePath){
		HyperTextArea.activeArea = this;
		if(!imagePath){
			imagePath = prompt('Enter Image URL:', 'http://');				
		}
		var oRTE;
		if (document.all) {
			oRTE = frames[this.name];
		} else {
			oRTE = document.getElementById(this.name).contentWindow;
		}

		if ((imagePath != null) && (imagePath != "")) {
			oRTE.focus()
			oRTE.document.execCommand('InsertImage', false, imagePath);
		}
		oRTE.focus()
	}
	
	//TODO should look into ways to make this cross browser and platform
	this.checkspell = function(){
		try {
			var tmpis = new ActiveXObject("ieSpell.ieSpellExtension");
			tmpis.CheckAllLinkedDocuments(document);
		}
		catch(exception) {
			if(exception.number==-2146827859) {
				if (confirm("ieSpell not detected.  Click Ok to go to download page."))
					window.open("http://www.iespell.com/download.php","DownLoad");
			} else {
				alert("Error Loading ieSpell: Exception " + exception.number);
			}
		}
		
	}
	
	this.select = function(menu,cmd){
		HyperTextArea.activeArea = this;
		var oRTE;
		if (document.all) {
			oRTE = frames[this.name];
		} else {
			oRTE = document.getElementById(this.name).contentWindow;
		}
		
		var idx = menu.selectedIndex;
		// First one is always a label
		if (idx != 0) {
			var selected = menu.options[idx].value;
			oRTE.document.execCommand(cmd, false, selected);
			menu.selectedIndex = 0;
		}
		oRTE.focus();
		
	}
	
	this.insertTableDialog = function(){
		w = window.open("","tableDialog","width=300,height=150");
		w.area = this;
		d = w.document;
		d.open();
		d.write(getTableDialogAsString());
		d.close();
		
	}
	this.insertTable = function(rows,cols,spacing,padding,border){
		rows = rows||3;
		cols = cols||3;
		spacing = spacing||2;
		padding = padding||2;
		if(border == true){
			border = 1;
		}
		border = border||0;
		
		if (document.all) {
			oRTE = frames[this.name];
		} else {
			oRTE = document.getElementById(this.name).contentWindow;
		}
		doc = oRTE.document;

		table = doc.createElement("table");
		table.setAttribute("border", border);
		table.setAttribute("cellpadding", padding);
		table.setAttribute("cellspacing", spacing);
		table.setAttribute("class", "hyperTable");
		
		for (var i=0; i < rows; i++) {
			var tr = doc.createElement("tr");
			for (var j=0; j < cols; j++) {
				var td = doc.createElement("td");
				var content = doc.createTextNode('\u00a0');
				td.appendChild(content);
				tr.appendChild(td);
			}
			table.appendChild(tr);
		}
		this.insertElement(table);
	}
	
	this.insertElement = function(el){
		if (document.all) {
			oRTE = frames[this.name];
		} else {
			oRTE = document.getElementById(this.name).contentWindow;
		}
		doc = oRTE.document;
		if (document.all) {
			selection = doc.selection;
			var html = el.outerHTML;
			var range = selection.createRange();
			try {
				range.pasteHTML(html);        
			} catch (e) {
				// catch error when range is evil for IE
			}
        }else{
        	selection = oRTE.getSelection();
			var range = selection.getRangeAt(0);
			selection.removeAllRanges();
			range.deleteContents();
			var container = range.startContainer||selection.focusNode;
			var pos = range.startOffset;
			afterNode = container.childNodes[pos];
			try{
				if (container.nodeName.toLowerCase() == "body" && pos < container.childNodes.length && container.childNodes[pos + 1]){
					afterNode = container.childNodes[pos+1]
					container.insertBefore(el, afterNode);
				}else{
					container.insertBefore(el, container.afterNode);
				}
			}catch (e){
				//if this is a text node, then break it up into a text node, new element, text node
				if(container.nodeName.toLowerCase() == "#text"){
					text0 = container.data.substring(0,range.startOffset);
					text1 = container.data.substring(range.startOffset,container.data.length-1);
					container.data = text0;
					parent = container.parentNode;
					parent.insertBefore(el,container.nextSibling);
					newTextNode = document.createTextNode(text1);
					parent.insertBefore(newTextNode,el.nextSibling);
				}else {
					alert(el.nodeName.toLowerCase() + " cannot be placed here for the following reason:\n\n" + e);
				}
			}
        }          
		
	}
	
	this.init();
	if(! this.delayRender){
		this.render(this.html);
	}

}

function TextFormatButton(name,label,icon,command,option){
	this.name = name;
	this.label = label;
	this.icon = icon;
	this.command = command;
	this.option = option||"";
	//the next two values are set by the HyperTextArea object
	this.area = null;
	this.resourcePath = null;
		
	this.getRenderedText = function(){
		text = '<td><div id="'+this.area.name+'_'+this.name+'">'
		text = text + '<img class="btnImage" src="'+this.resourcePath+this.icon+'" width="25" height="24" alt="'+this.label+'" title="'+this.label+'" onClick="HyperTextArea.getArea(\''+ this.area.name +'\').getControl(\''+this.name+'\').execute()">';
		text = text + '</div></td>';		
		return text;
	}
	

	this.execute = function(){
		this.area.formatText(this.command,this.option);
	}
}

function Button(name,icon,title,methodName){
	this.name=name;
	this.getRenderedText = function(){
		text = '<td><div id="'+name+'">'
		text = text + '<img class="btnImage" src="'+this.resourcePath+icon+'" width="25" height="24" alt="'+title+'" title="'+title+'" onClick="HyperTextArea.getArea(\''+ this.area.name +'\').'+methodName+'()">';
		text = text + '</div></td>';		
		return text;
	}
}

function Spacer(name){
	this.name = name
	this.getRenderedText = function(){
		return '<td>&nbsp;</td>'
	}
}
function Toolbar(name, isFirstToolbar){
	this.name = name
	this.isFirstToolbar = isFirstToolbar||false;
	this.getRenderedText = function(){
		this.area.toolbarNames[this.area.toolbarNames.length] = this.name;
		text = '<table id="' + this.name + '_' + this.area.name + '" cellpadding="1" cellspacing="0"><tr>'
		if(this.isFirstToolbar){
			text = '</tr></table>\n' + text;
		} 
		return text; 
	}
}

function Menu(name,cmd){
	this.name = name;
	this.cmd = cmd;
	this.area = null;
	this.items = new Array();
	this.addItem = function(value,lable){
		this.items[this.items.length] = new MenuItem(value,lable);
	}
	this.addItems = function(){
		for (i=0;i<arguments.length;i=i+2){
			this.addItem(arguments[i],arguments[i+1]);
		}
	}
	this.getRenderedText = function(){
		text = "<td><select name='"+this.name+"' id='"+this.name+"_"+this.area.name+"' onchange='HyperTextArea.getArea(\""+ this.area.name +"\").select(this,\""+this.cmd+"\");'>\n";
		for (i=0;i<this.items.length;i++){
			thisItem = this.items[i]
			text = text + "<option value='"+thisItem.value+"'>"+thisItem.lable+"</option>\n";
		}
		text = text + "</select></td>";
		return text;
	}
}

function MenuItem(value,lable){
	this.value = value;
	this.lable = lable;
}

HyperTextArea.areas = new Array();
HyperTextArea.getArea = function(name){
	return HyperTextArea.areas[name];
}
HyperTextArea.activeArea = null;
HyperTextArea.about = function(){
	var area;
	for(i in HyperTextArea.areas){
		area = HyperTextArea.getArea(i);
		break;
	}
	window.open(area.resourcePath + "about.html");
}
HyperTextArea.updateAllAreas = function(){
	//iterate over all areas and call update
	for(i in HyperTextArea.areas){
		area = HyperTextArea.areas[i];
		area.update();
	}
}
HyperTextArea.forms = new Array();

function getOffsetTop(elm) {
	var mOffsetTop = elm.offsetTop;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent){
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	
	return mOffsetTop;
}

function getOffsetLeft(elm) {

	var mOffsetLeft = elm.offsetLeft;
	var mOffsetParent = elm.offsetParent;
	
	while(mOffsetParent) {
		mOffsetLeft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	
	return mOffsetLeft;
}

function kb_handler(evt, rte) {
	//contributed by Anti Veeranna (thanks Anti!)
	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = '';
		switch (key) {
			case 'b': cmd = "bold"; break;
			case 'i': cmd = "italic"; break;
			case 'u': cmd = "underline"; break;
		};

		if (cmd) {
			evt.target.ownerDocument.execCommand(cmd,false,true);
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}

function stripHTML(oldString) {
	var newString = oldString.replace(/(<([^>]+)>)/ig,"");
	
	//replace carriage returns and line feeds
	newString = escape(newString)
	newString = newString.replace("%0D%0A"," ");
	newString = newString.replace("%0A"," ");
	newString = newString.replace("%0D"," ");
	newString = unescape(newString)
	
	//trim string
	newString = trim(newString);
	
	return newString;
}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
}

function getPaletteAsString(){
	hexArray = new Array("00","55","AA","FF");
	out = "";
	out2 = "";
	line = ""
	row = 1;
	count = 1;
	for(i=hexArray.length-1;i>=0;i--){
		val0 = hexArray[i];
		for(j=hexArray.length-1;j>=0;j--){
			val1 = hexArray[j];
			for(k=hexArray.length-1;k>=0;k--){
				val2 = hexArray[k];
				hexVal = val0+val1+val2;
				line = line + "\n <td id='#"+hexVal+"' bgcolor='#"+hexVal+"' width='15' height='15' onmouseover='this.style.border=\"1px dotted white\"' onmouseout='this.style.border=\"1px solid gray\"' onclick='area.setColor(this.id)'><img width='1' height='1'></td>";
				if(count==1 || (row % 2) == 0){
					if(((count - 1) % 8) == 0){
						out = out + "\n<tr>";
						row++
					}
					out = out + line;
					if((count % 8) == 0){
						out = out + "\n</tr>";
					}
				}else{
					if(((count - 1) % 8) == 0){
						out2 = out2 + "\n<tr>";
						row++
					}
					out2 = out2 + line;
					if((count % 8) == 0){
						out2 = out2 + "\n</tr>";
					}
				}
				line = "";
				count++;
			}
		}
	}
	out = '<table cellpadding="0" cellspacing="1" border="1" align="center">' + out + out2 + "</table>";
	return out;
}

function getTableDialogAsString(){
	out = '<form name="tableDialog">';
	out = out + '<table width="100%" cellpadding="2" cellspacing="2" border="0">';
	out = out + '<tr>';
	out = out + '<td>Rows: <input type="text" name="rows" size="2" value="3"/></td>';
	out = out + '<td>Columns: <input type="text" name="cols" size="2" value="3"/></td>';
	out = out + '</tr>';
	out = out + '<tr>';
	out = out + '<td>Spacing: <input type="text" name="spacing" size="2" value="2"/></td>';
	out = out + '<td>Padding: <input type="text" name="padding" size="2" value="2"/></td>';
	out = out + '</tr>';
	out = out + '<tr>';
	out = out + '<td colspan="2">Border: <input type="checkbox" name="border" value="1"/></td>';
	out = out + '</tr>';
	out = out + '<tr>';
	out = out + '<td colspan="2"><div align="center"><input type="button" name="cancel" value="Cancel" onclick="self.close()"/><input type="button" name="button" value="Insert Table" onclick="window.opener.HyperTextArea.activeArea.insertTable(this.form.rows.value,this.form.cols.value,this.form.spacing.value,this.form.padding.value,this.form.border.checked);self.close()"/></div></td>';
	out = out + '</tr>';
	out = out + '</table>';
	out = out + '</form>';
	return out;
}
function enableDesignMode(areaName){
	try{
		if (document.all) {
			frames[areaName].document.designMode = "On";
		}else{
			contentDocument = document.getElementById(areaName).contentDocument;
			contentDocument.designMode = "on";
		}	
		self.status = "";
		area.setContent(area.html)
	}catch(e){
		//attempt to recover from any exceptions
		exp = "enableDesignMode('"+areaName+"')";
		area = HyperTextArea.getArea(areaName);
		area.designModeRetryCount++
		self.status = "Error in setting designMode property on attempt number "+ area.designModeRetryCount +".  Retrying.";
		if(area.designModeRetryCount <= 10){
			t = setTimeout(exp,100);
		}else{
			self.status = areaName + " failed to initialize properly";
			throw e;
		}
	}
}

function onHyperTextAreaLoad(areaName) {
	self.status = "attempting to set designMode property";
	area = HyperTextArea.getArea(areaName);
	area.cpWindow = frames['cp' + areaName].window;
	
	//enables the area to determine what form it belongs to
	area.form = document.getElementById("hdn"+areaName).form;
	
	//attaches to the forms submit handler only once
	formAlreadyStored = false;
	for(i=0;i<HyperTextArea.forms.length;i++){
		if(area.form == HyperTextArea.forms[i]){
			formAlreadyStored = true;
			break;
		}
	}
	if(!formAlreadyStored){
		onSubmitFunc = area.form.onsubmit;
		area.form.onsubmit = function(){
			HyperTextArea.updateAllAreas();
			if(onSubmitFunc){
				onSubmitFunc();
			}
		}
		HyperTextArea.forms[HyperTextArea.forms.length] = area.form;
	}
	area.setContent(area.html)
	if (document.all) {
		cp = frames["cp" + areaName];
		cp.document.write(getPaletteAsString());
	} else {
		cp = document.getElementById("cp"+areaName);
		d = cp.contentDocument;
		d.open();
		d.write(getPaletteAsString());
		d.close()
	}
	enableDesignMode(areaName);
	area.setContent(area.html)
}

//Editor code start i.e. frame box buttons code like LEFT,RIGHT, BOLD AND ITALIC
var Editor;
var status = new Array();
var position;
function Format(action, newClass, divID){ 
	Editor.execCommand(action, false, null);
	switch(divID){
		case 'answerbox_button_bold':
			position = status.indexOf('B'); 
			if(isValueInArray(status, 'B')){
				document.getElementById(divID).setAttribute("class", '');
				
				status.splice(position, 1) ;
			}
			else{
				status.push("B");
				document.getElementById(divID).setAttribute("class", newClass);
			}
		break;
		case 'answerbox_button_italic':
			position = status.indexOf('I'); 
			if(isValueInArray(status, 'I')){
				document.getElementById(divID).setAttribute("class", '');
				status.splice(position, 1) ;
			}
			else{
				status.push("I");
				document.getElementById(divID).setAttribute("class", newClass);
			}
		break;
		case 'answerbox_button_underline':
			position = status.indexOf('U'); 
			if(isValueInArray(status, 'U')){
				document.getElementById(divID).setAttribute("class", '');
				status.splice(position, 1) ;
			}
			else{
				status.push("U");
				document.getElementById(divID).setAttribute("class", newClass);
			}
		break;
		case 'answerbox_button_left':
			position = status.indexOf('L'); 
			if(isValueInArray(status, 'L')){
				document.getElementById(divID).setAttribute("class", '');
				status.splice(position, 1) ;
			}
			else{
				status.push("L");
				document.getElementById(divID).setAttribute("class", newClass);
			}
		break;
		case 'answerbox_button_right':
			position = status.indexOf('R'); 
			if(isValueInArray(status, 'R')){
				document.getElementById(divID).setAttribute("class", '');
				Editor.execCommand('justifyleft', false, null);
				status.splice(position, 1) ;
			}
			else{
				status.push("R");
				document.getElementById(divID).setAttribute("class", newClass);
			}
		break;
		case 'answerbox_button_center':
			position = status.indexOf('C'); 
			if(isValueInArray(status, 'C')){
				document.getElementById(divID).setAttribute("class", '');
				Editor.execCommand('justifyleft', false, null);
				status.splice(position, 1) ;
			}
			else{
				status.push("C");
				document.getElementById(divID).setAttribute("class", newClass);
			}
		break;
	}
}
 
/*function Colour(colour){		
	Editor.execCommand("forecolor",false, colour);
}*/
/*
window.onload = function(){
	Editor = document.getElementById('textbox').contentWindow.document;
	Editor.designMode = "on";
	document.forms[0].onsubmit = function(){
		var text = document.getElementById('textbox');
		text.value = Editor.body.innerHTML;
	}
}
*/
function isValueInArray(arr, val) {
	inArray = false;
	for (i = 0; i < arr.length; i++)
		if (val == arr[i])
			inArray = true;
	return inArray;
}

	//FACEBOOK CODE START 

	function gup( name )	{
  		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
		return "";
		else
		return results[1];
	}

	function auth_fb(channel) {
	if(channel) {
		var chl = '1';
	}
	
    	var viewer  = FB.Facebook.apiClient.fql_query(
          'SELECT name, proxied_email, pic_square_with_logo ,profile_url,uid FROM user WHERE uid='+FB.Facebook.apiClient.get_session().uid,
    
        function(results) {
	        load_data(results[0].name,results[0].proxied_email,
                results[0].pic_square_with_logo,
                results[0].profile_url,
                'FB.Connect.logout();return false;',results[0].uid,chl)
          });
		//callqueryForPhotos();
    	}
		
	function load_data(name, email, image, url, logout,profileId,chl) { 
	 $('#user').html( "<div class='profile_FacebookImg'><a href='"+url+"'>"
     	+ "<img alt='"+name+"' src='"+image+"' border='0' /></a></div>"
	 	+ "<span id='ubname'>Welcome, <a href='"+url+"'>" + name + "</a></span>"
	 	+ "<br />You are signed in with your Facebook account"
     	+ "<div class='clickhereSignOutlink'><a href='#comments-form' autologoutlink='true' onclick='" + logout + "'>click here to sign out.</a></div>" ).show(); 

	var newURL = location.href;
	var result = newURL.indexOf("?");
	var question_id;
	if(chl != 1){
		if(result == 1){
			question_id = gup('question_id');
			newURL += '&fuid='+profileId+'&login_user='+name+'&logout='+logout+'&answer='+document.getElementById("text_"+question_id).value+'&question='+document.getElementById("q_title1").value; 
			window.location = newURL;
		}
		else	{
			newURL += '/?fuid='+profileId+'&login_user='+name+'&logout='+logout+'&question='+document.getElementById("q_title").value;	
			window.location = newURL;
		}
	}
	else {
		if(result == 1){
			question_id = gup('question_id');
			newURL += '&fuid='+profileId+'&login_user='+name+'&logout='+logout+'&answer='+document.getElementById("text_"+question_id).value+'&question='+document.getElementById("q_title1").value; 
			window.location = newURL;
		}
		else{ 
			newURL +=  '?fuid='+profileId+'&login_user='+name+'&logout='+logout+'&question='+document.getElementById("q_title1").value; 
			window.location = newURL;
		}
	}
	}

	function onNotConnected(){ 
		get("facebookText").style.display = "block";
	 	get("profile_commentText").style.display = "block";
	 	get("profile_Name").style.display = "block";
	 	get("profile_Url").style.display = "block";
		get("name").value = "";
    		get("url").value = "";
		var elem = get("user");
		elem.innerHTML = "<fb:login-button onlogin='auth_fb();'></fb:login-button>"
		FB.XFBML.Host.parseDomElement(elem);
		document.forms['commentForm'].removeChild(get("profileId"));
		get("commentForm").removeChild(get("profileId"));
		var ajaxSubmissionMsg = get('ajaxSubmissionMsg');
		if(ajaxSubmissionMsg != null){
			ajaxSubmissionMsg.innerHTML = "";
		}
	}
	
	function publishStream(text){
		//var creatorTitle = document.forms['commentForm'].creatorTitle.value ;
		//var entryLink = document.forms['commentForm'].entryLink.value ;
		var creatorTitle = text;
		var entryLink = location.href;
		var attachment = {'name':creatorTitle,'href':entryLink,'description':text};
		FB.Connect.streamPublish('', attachment);
		//return true;
		
	 }	  
	 function fb_reg(commentTxtArea){	
		var text = document.getElementById(commentTxtArea).value;
		//var text = document.forms['answer_form'].commentTxtArea.value ;
		var data = {"comment": text};     
		return publishStream(text);
     }
		
	//FACEBOOK CODE END 
