/**************************************
 *
 * 		MAIN JS File
 *
 *		Holds js-functions used
 *		around all pages
 *
 **************************************/

    /************************************
	 * AJAX BASIS FUNCTIONS
	 ************************************/
function updateContent(script,block)
{
    new Request.HTML({
    url: script,
    method: 'get',
    update: block,
    onComplete: function(){}
    }).send();
}
function updateJSONContent(script,block)
{
    new Request.JSON({
    url: script,
    method: 'get',
    onSuccess: function(content){
    $(block).set('html', content.ret);
    }}).get();
}
function sendRequest(script)
{
    var req = new Request({method: 'get', url: script});
    req.send();
}
function sendPostRequest(script,formdata)
{
    var req = new Request({url: script});
    req.post({data: formdata});
}
function getPanelContent(pars,id)
{
   /*
    var jsonRequest = new Request.JSON({url: "ajax_get_panel_content.php"+pars+"&id="+id,
    onRequest: function() { $('ibeta').set('src', 'img/beta_label.gif'); $('tb_'+id).set('slide', {duration: 'long', transition: 'bounce:out'}).slide('out'); },
    onComplete: function() { $('ibeta').set('src', 'img/beta_label.png'); },
    onSuccess: function(content){
    $('tb_'+id).set('html', content.txt);
    $('sm_'+id).set('html', content.more);
    $('tb_'+id).set('slide', {duration: 'long', transition: 'bounce:out'}).slide('in');

    }}).get();
    */
}
function getSlideElement(el_id)
{
    if($(el_id).getStyle('display') == 'none')
    {
        $(el_id).setStyle('display', 'block');
    }
    else
    {
        $(el_id).setStyle('display', 'none');
    }

    //$(el_id).set('slide', {duration: 'long', transition: 'bounce:out'}).slide('in');
}
    /************************************
	 * USER SELECTION FUNCTIONS
	 ************************************/
function removeUserCard(select_pk, insert_field)
{
    var currentList = $(insert_field).get('value');
    var currentListArray = currentList.split(',');
    var i;
    var cleanList = '';
    var strict=false;
    for(i=0; i<currentListArray.length; i++)
    {
        if (currentListArray[i] != select_pk) {
    	    if(cleanList!='') cleanList += ',';
    	    cleanList += ''+currentListArray[i];
        }
    }
    $(insert_field).set('value', cleanList);
    $(insert_field+'_usr_card_'+select_pk).dispose();
}
function selectUserMultiSingle(select_pk, insert_field){
	var currentList = window.opener.document.getElementById(insert_field).value;
    var currentListArray = currentList.split(',');
    if(currentListArray.indexOf(select_pk) < 0)
    {
        selectUserMultiSingle2(select_pk, insert_field, currentListArray);
	    window.close();
    }
    else
    {
        window.close();
    }
}
function selectUserMultiSingle2(select_pk, insert_field, currentListArray){

  if(!isNaN(select_pk)){
     if(window.opener.document.getElementById(insert_field).value != "")
     {
         window.opener.document.getElementById(insert_field).value += ',';
     }
     window.opener.document.getElementById(insert_field).value += select_pk;



    var insertBoxValue = window.opener.document.getElementById('mess_receivers').get('html') ;
    window.opener.document.getElementById('mess_receivers').set('html',"<div id='users_to_usr_card_"+select_pk+"'></div>"+insertBoxValue);
    var usrCard = $('user_card_'+select_pk).getChildren().get('html');
    //var usrHandle = $('handle_remove_'+select_pk).get('html');
    var out = usrCard;
    window.opener.document.getElementById('users_to_usr_card_'+select_pk).set('html',out);
    window.opener.document.getElementById('mess_receivers').setStyles({
                                                                          border: '1px solid #999999',
                                                                          background: '#FFF url(../template/v3/green/img/input_txt_bg.gif) top left repeat-x'
                                                                      });
  }
}

// User Profile


// User Gallery
function setAvatar(us_id,ava_file_name)
{
    $('usercard_img').erase('src');
    $('usercard_img').set('src','pic/half/'+ava_file_name+'.jpg');
    $('profile_img').erase('src');
    $('profile_img').set('src','pic/slim/'+ava_file_name+'.jpg');
    sendRequest('ajax_set_avatar.php?us_id='+us_id+'&file_name='+ava_file_name);
}
function unsetAvatar(us_id,us_gender)
{
    if(us_gender == 0)
    {
        us_gender = 1;
    }
    $('usercard_img').erase('src');
    $('usercard_img').set('src','template/v3/img/ava_'+us_gender+'_50.png');
    $('myprofile_img').erase('src');
    $('myprofile_img').set('src','template/v3/img/ava_'+us_gender+'_50.png');
    $('profile_img').erase('src');
    $('profile_img').set('src','template/v3/img/ava_'+us_gender+'_210.png');
    sendRequest('ajax_set_avatar.php?us_id='+us_id+'&unset=1');
}
function showhideDiv(div_id)
{
    if($(div_id).getStyle('display') == 'none')
    {
        $(div_id).setStyle('display', 'block');
    }
    else
    {
        $(div_id).setStyle('display', 'none');
    }
}

function toggleSlide(divid)
{
    var mySlider = new Fx.Slide(divid, {duration: 500});
    mySlider.toggle(); 
}
function showhideDivByChecked(div_id,check)
{
    if($(div_id).getStyle('display') == 'none' && check == true)
    {
        $(div_id).removeProperty('style');
    }
    else
    {
        $(div_id).setProperty('style', 'display:none;');
    }
}


// DOM READY
window.addEvent('domready', function() {
    $('logo').addEvent('click', function(e) {
         e.stop();
        window.location = './';
        }
    );
    /*
    if($('sb_friend') != null && myfriends_cnt > 0)
    {
        updateContent('ajax_sb_friend.php?upk='+myfriends_upk+'&ulan='+myfriends_lan,'sb_friend');
        if($('friends_count') != null)
        {
             //var val = $('friends_count').get('value');
             //$('friends_count').set('value',val+' ('+myfriends_cnt+')');
            $('friends_count').set('text', ' ('+myfriends_cnt+')');
        }
    }
    */
    if($("login_usr") != null)
    {
         $("login_usr").focus();
        window.addEvent("keydown", function(e){
          //e.stop();
            if (e.key=="enter" && $("login_usr").get("value") != "" && $("login_pwd").get("value") != "") {
            $("loginform").submit();
          }
        });
    }
    var item_labels = $$(".vote_item_label");

        item_labels.each(function(item, index){
            item.addEvent("mouseover", function(event){
                event.stop();
                item.setStyle("color","#333");
            });
            item.addEvent("mouseout", function(event){
                event.stop();
                item.setStyle("color","#666");
            });
        });


});

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

/************************************
* VOTES
************************************/
function setVoteRadioItem(vpk,val)
{
    var fields = $$(".vote_item_field");
    fields.each(function(item, index){
        var el_id = item.getProperty("id");
        if(el_id == "vote_item_field_"+val)
        {
            item.addClass("active");
            var hfield = $("vote_result_"+vpk);
            if(hfield != null)
            {
                hfield.set("value",val);
            }

        }
        else
        {
            if(item.hasClass("active"))
            {
                item.removeClass("active");
            }
        }
    });
}
function setVoteCheckItem(vpk,val)
{
    var fields = $$(".vote_item_field");
    fields.each(function(item, index){
        var el_id = item.getProperty("id");
        if(el_id == "vote_item_field_"+val)
        {
            if(item.hasClass("active"))
            {
                item.removeClass("active");
                $("vote_result_"+val).set("value","");
            }
            else
            {
                 item.addClass("active");
                 $("vote_result_"+val).set("value",val);
            }
        }

    });
}


/************************************
* USER SELECTION FUNCTIONS
************************************/

function popSelectUser(type, varname){
	var SelectPicWindow = window.open('index.php?sec=friendselector&popupMode=1&insert_field='+varname+'&type='+type,'popup','location=0,menubar=0,status=0,scrollbars=0,resizable=1,width=525,height=700');
}
function reloadCaptchaDiv(baseUrl)
{
	var now = new Date();
	var nuSrc = baseUrl+'&time=' + now.getTime();
	document.getElementById('captcha_img').src = nuSrc;
}
function hideToolbarLinks(id)
{
    $("toolbar_links_"+id).setStyle("display","none");
    $("tollbar_gear_"+id).setStyle("display","block");
}
function showToolbarLinks(id)
{
    $("toolbar_links_"+id).setStyle("display","block");
    $("tollbar_gear_"+id).setStyle("display","none");
}


// Comments
function liveCommInput(id,type)
{
  $("comm_input_click_"+id).setStyle("display","none");
  $("comm_input_form_"+id).setStyle("display","block");
  $("comm_save_button_"+id).setStyle("display","block");
  $("comm_input_field_"+id).focus();
}

function saveComment(id,type)
{
    var inp_field = $("comm_input_field_"+id);
    var txt = inp_field.get("value");
    if(txt == "" || txt == "Please don't flood")
    {
        $("comm_input_field_"+id).focus();
        return false;
    }
    else
    {
      var data = {
              "id":id,
              "txt":txt,
              "lan": lan,
              "type": type
              };
      new Request.JSON({
      url: script,
      onSuccess: function(content){
          if(content.error != "")
          {
              inp_field.set("value",content.error);
          }
          else
          {
             $("comm_save_button_"+id).setStyle("display","none");
             $("comm_input_form_"+id).setStyle("display","none");
             $("comm_input_click_"+id).setStyle("display","block");
             if(typeof redirect != "undefined")
             {
                  window.location.href = redirect+id;
             }
             else if(content.success != "")
             {
                if(content.success == "page_reload")
                {
                    window.location.href = "/?sec=community&show=share";
                }

                  var target = $("comm_lines_wrapper_"+id);
                  var exposed_lines = target.getChildren(".exposed");
                  if(exposed_lines.length == 3)
                  {
                      var exposed_first = exposed_lines[0];
                      exposed_first.removeClass('exposed');
                      exposed_first.addClass("latent");
                      exposed_first.setStyle("display","block");
                  }
                  var newlinecomm = new Element ("div");
                  newlinecomm.addClass("comm_line");
                  newlinecomm.addClass("exposed");
                  newlinecomm.set('styles', {
                      "width": '384px',
                      "border-radius": '4px',
                      "margin": '0 0 5px 63px'
                  });
                  newlinecomm.set("html",content.success);
                  newlinecomm.inject(target,"bottom");

                  /*

                  var necomm = $("newcomm_"+id);
                  var newlinecomm = new Element ("div");
                  newlinecomm.set("html",content.success);
                  newlinecomm.inject(necomm,"bottom");
                  */
                  $("comm_input_field_"+id).set("value","");
                  var commcnt = $("commcnt_"+id);
                  if(commcnt != null)
                  {
                      commcnt.set("text",parseInt(commcnt.get("text"))+1);
                  }

                  //necomm.removeProperty("id");
                  //var newnewcomm = new Element ( "div" , { "id" : "newcomm_"+id });
                  //necomm.getParent().inject(newnewcomm,"before");

             }
          }
      }}).post(data);
    }
}
function wait(msecs)
{
    var start = new Date().getTime();
    var cur = start
    while(cur - start < msecs)
    {
        cur = new Date().getTime();
    }
}
function submitVote()
{
    var args = submitVote.arguments;
    var res = new Array();
    var type = '';
    var tmp = '';
    var sendAnswer = false;
    if(args.length >= 2)
    {
        if(args[1] == 0)
        {
            tmp = $('vote_result_'+args[0]).get('value');
            if(tmp != '')
            {
                sendAnswer = true;
                res.push(tmp);
                type = 'single';
            }
        }
        else if(args[1] == 1)
        {
            type = 'multi';
            for(i=2;i<args.length;i++)
            {
                tmp = $('vote_result_'+args[i]).get('value');
                if(tmp != '')
                {
                    sendAnswer = true;
                    res.push(tmp);
                }
            }
        }
        if(sendAnswer)
        {
            var data = {
              "vpk":args[0],
              "type":type,
              "res": res
            };
            new Request.JSON({
                url: 'ajax_submit_vote.php',
                onSuccess: function(content){
                if(content.error != "")
                {


                }
                else if(content.success != "")
                {
                    var target = $('iyo_vote_'+args[0]);
                    target.fade('hide');
                    target.set('html',content.success);
                    target.fade('in');
                }
                }}).post(data);
        }
    }
}



// OLLI
function getXMLHTTP() { //function to return the xml http object
	var xmlhttp=false;
	try{
		xmlhttp=new XMLHttpRequest();
	}
	catch(e)	{
		try{
			xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e){
			try{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e1){
				xmlhttp=false;
			}
		}
	}

	return xmlhttp;
}
function show_comments(id) {
	var strURL="ajax_comments.php?survey_id="+id+"&action=show";
	var req = getXMLHTTP();
	if (req) {
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
		  divid="survey_"+id;
					document.getElementById(divid).innerHTML=req.responseText;
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}
		}
		req.open("GET", strURL, true);
		req.send(null);
	}
}

function hide_comments(id) {
	var strURL="ajax_comments.php?survey_id="+id+"&action=hide";
	var req = getXMLHTTP();
	if (req) {
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
		  divid="survey_"+id;
					document.getElementById(divid).innerHTML=req.responseText;
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}
		}
		req.open("GET", strURL, true);
		req.send(null);
	}
}

function add_comment(id) {
var strURL="ajax_comments.php?survey_id="+id+"&action=add";
	var req = getXMLHTTP();
	if (req) {
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
   			        divid="survey_"+id;
					document.getElementById(divid).innerHTML=req.responseText;
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}
		}
		req.open("GET", strURL, true);
		req.send(null);
	}
}

function del_comment(id,msgid) {
	var strURL="ajax_comments.php?survey_id="+id+"&action=del&msgid="+msgid;
	var req = getXMLHTTP();
	if (req) {
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
		  divid="survey_"+id;
					document.getElementById(divid).innerHTML=req.responseText;
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}
		}
		req.open("GET", strURL, true);
		req.send(null);
	}
}

function save_comment(id,text) {
  var strSingleLineText = text.replace(new RegExp( "\\n", "g" ), "<br>");
var strURL="ajax_comments.php?survey_id="+id+"&action=save&text="+strSingleLineText;
	var req = getXMLHTTP();
	if (req) {
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				// only if "OK"
				if (req.status == 200) {
   			        divid="survey_"+id;
					document.getElementById(divid).innerHTML=req.responseText;
				} else {
					alert("There was a problem while using XMLHTTP:\n" + req.statusText);
				}
			}
		}
		req.open("GET", strURL, true);
		req.send(null);
	}
}


function startUpload(){
      document.getElementById('f1_upload_process').style.visibility = 'visible';
      document.getElementById('f1_upload_form').style.visibility = 'hidden';
      return true;
}

function stopUpload(success){
      var result = '';
      if (success == 'error'){
         result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
      }
      else {
         result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/><span class="msg">' + success + '<\/span><br/><br/>';
      }
      document.getElementById('f1_upload_process').style.visibility = 'hidden';
      document.getElementById('f1_upload_form').innerHTML = result + '<label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
      document.getElementById('f1_upload_form').style.visibility = 'visible';
      return true;
}




