// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function toggleDisp() {
    for (var i=0;i< arguments.length;i++){
        var d = $(arguments[i]);
        if (d.style.display == 'none')
            d.style.display = 'block';
        else
            d.style.display = 'none';
    }
}

function toggleTab(num, subnum, numelems) {
    if ($('tabContent_'+num+'_'+subnum).style.display == 'none'){
        for (var i=0; i< numelems; i++) {
	  var temph = 'tabHeader_'+num+'_'+i;
          var h = $(temph);
          if (!h){
            var h = $('tabHeaderActive_'+num);
            h.id = temph;
          }
          var tempc = 'tabContent_'+num+'_'+i;
          var c = $(tempc);
          if(c.style.display != 'none'){
            toggleDisp(tempc);
          }
        
        }
        var h = $('tabHeader_'+num+'_'+subnum);
        if (h) {
            h.id = 'tabHeaderActive_'+num;
	}
        h.blur();
        var c = $('tabContent_'+num+'_'+subnum);
        toggleDisp('tabContent_'+num+'_'+subnum);
    }
}
function addFileInputTo(element) {
    createNewParagraphWithFileInputIn(element);

    // If there alread are any file inputs for some objects, get highest ID and return ID + 1
    function fetchHighestImageID(element) {
	var index = 0;
	var paragraphs = element.previous().select('p');
	if( paragraphs.length > 0) {
	    index = parseInt(paragraphs.pluck('id').max(),10) + 1;
	}
	return index;
    }

    function createNewParagraphWithFileInputIn(element) {
	// Fetch unique number for new input field
	var inputs_number = fetchHighestImageID(element) + element.select('p').length - 1; // Don't count "add field" link
	var image_caption = 'image['+inputs_number+'][caption]';
	var image_data = 'image['+inputs_number+'][uploaded_data]';
	// Create all elements
	var para = new Element('p');
	var file_input = new Element('input', { 'type': 'file', 'name': image_data, 'id': image_data });
	var caption_label = new Element('label', { 'for': image_caption }).update(" Opis ");
	var caption_input = new Element('input', { 'type': 'text', 'name': image_caption, 'id': image_caption });
	var remove_link = new Element('span').
	    update(' Usuń').
	    observe('click', function(event){ removeFileInput(event); });

	// Add all elements into paragraph
	para.insert(file_input);
	para.insert(caption_label);
	para.insert(caption_input);
	para.insert(remove_link);
	
	// Add new paragraph before "add new image" link
	var add_image_para = element.down('a').up();
	add_image_para.insert({before: para});
	return para;
    }

    function removeFileInput(event) {
	var remove_image_para = event.target.up();
	var add_image_link = remove_image_para.nextSiblings().last().down('a');
	var container = remove_image_para.up('div');
	remove_image_para.remove();
    }
}


function taggle_menu(id) {
    if($(id).style.display=='none'){
	setTimeout("Effect.BlindDown('"+id+"',{duration:0.3})",500);
    }else {
	setTimeout("Effect.BlindUp('"+id+"',{duration:0.3})",500);
    }
}

function addCategoryForProduct(product, divId) {
    var catName = $("as_category_"+divId).getElementsByTagName('input')[0].value;
    new Ajax.Request('/admin/product/update_category?product_id='+product+'&cat_name='+catName+'&div_id='+divId, {async:true, evalScripts:true});
    return false;
}

function setArticleCategoryStatus(cat_article_id){
    new Ajax.Request('/admin/cat_article/set_status?category_id='+cat_article_id, {async:true, evalScripts:true});
}

function setArticleStatus(article_id){
    new Ajax.Request('/admin/article/set_status?article_id='+article_id, {async:true, evalScripts:true});
}

function setArticleAccessLevel(article_id){
    new Ajax.Request('/admin/article/set_access_level?article_id='+article_id, {async:true, evalScripts:true});
}

function setCategoryStatus(category_id){
    new Ajax.Request('/admin/category/set_status?category_id='+category_id, {async:true, evalScripts:true});
}

function setProductStatus(product_id){
    new Ajax.Request('/admin/product/set_status?product_id='+product_id, {async:true, evalScripts:true});
}

function setGalleryStatus(gallery_id){
    new Ajax.Request('/admin/gallery/set_status?gallery_id='+gallery_id, {async:true, evalScripts:true});
}

function setGalleryPrize(gallery_id){
    new Ajax.Request('/admin/gallery/set_prize?gallery_id='+gallery_id, {async:true, evalScripts:true});
}

function changeForumStatus(forum_id){
    forum_status = document.getElementById("forum_"+forum_id).value;
    new Ajax.Request('/admin/forums/change_forum_status?forum_id='+forum_id+'&forum_status='+forum_status, {asynchronous:true, evalScripts:true});
    alert("Status zmieniony");
}

function showNewsletterBox(){
    //    new Ajax.Updater('szukaj','/newsletter/show_newsletter_box', {asynchronous:true, evalScripts:true});
    new Ajax.Request('/newsletters/show_newsletter_box', {asynchronous:true, evalScripts:true});
}

function showSearchBox(){
    new Ajax.Request('/search/show_search_box', {asynchronous:true, evalScripts:true});
}

function updateTotalUnitPrice(qty,el){
    var qty = $(qty).value;
    new Ajax.Request('/shopping_cart/update_total_unit_price?id='+el+'&qty='+qty, {asynchronous:true, evalScripts:true});
}
function updateFund(val){
      var fund = 0;
      if ($('fund').checked==true)
       {fund = 1;}
	new Ajax.Request('/shopping_cart/update_fund?fund='+fund, {asynchronous:true, evalScripts:true});
}
function updateFund2(val){
  new Ajax.Request('/shopping_cart/update_fund?fund='+val, {asynchronous:true, evalScripts:true});
}


function getUserBillingData(){
    document.getElementById("shipping_address_first_name").value = document.getElementById("billing_address_first_name").value;
    document.getElementById("shipping_address_last_name").value = document.getElementById("billing_address_last_name").value;
    document.getElementById("shipping_address_street").value = document.getElementById("billing_address_street").value;
    document.getElementById("shipping_address_apartment").value = document.getElementById("billing_address_apartment").value;
    document.getElementById("shipping_address_zip_code").value = document.getElementById("billing_address_zip_code").value;
    document.getElementById("shipping_address_city").value = document.getElementById("billing_address_city").value;
    document.getElementById("shipping_address_phone").value = document.getElementById("billing_address_phone").value;

    //  var addressForm = $("billing_form");
    // for(var i=0;i<addressForm.elements.length;i++){
    //  	alert(addressForm.elements[i].value);
    // }
}

function changeProducts(element,mainEl){
    var mainChkbx=$('mCheck').checked 
    var checkboxes=$(element).getElementsByTagName('input');

    if(mainChkbx == true){
	for(var i=0;i<checkboxes.length;i++){
	    checkboxes[i].checked = true;   
	}
    }
    else{
	for(var i=0;i<checkboxes.length;i++){
	    checkboxes[i].checked = false;
	}
    }
}

function onOffMonitorForm(value){
    $('email').disabled = value;
    $('password').disabled = value;
}


function sendNewForumMonitoringPassword(forum_id){
    var email = $('forum_monitoring_email_forgot').value;
    new Ajax.Request('/forums/send_new_forum_monitoring_password?forum_id='+forum_id+'&email='+email, {async:true, evalScripts:true});
}

function saveSequence(){
    li_list = document.getElementsByTagName('li');
    
    var ids = new Array();
    
    for(var i=0; i<li_list.length;i++){
	if (li_list[i].id != ''){
	    ids.push(li_list[i].id);
	}
    }
    new Ajax.Request('/admin/cat_article/save_sequence?ids='+ids, {async:true, evalScripts:true});
}

 function validate_survey(survey_num)
  {
    var temp = new Array();
    var licz = 0;
    temp = $('lista').value.split(','); 
    for (i=0;i<=temp.length-1;i=i+1) 
	{
        id_p = temp[i];
		 $('set_'+id_p).className="survey_question"
        if (document.getElementById('p'+id_p).value=='') 
		{ 
		//alert('Nie odpowiedziano na pytanie '+id_p); 
          licz = licz + 1; 
		  $('set_'+id_p).className="survey_question_warning"
        } 
	}

    if ( licz > 0 ) 
	{
      alert('Proszę udzielić odpowiedzi na wszytkie wymagane pytania !'); 
      return false;
    } 
	else 
	{ return true; }
  }
  
  function znacz(id, wartosc)
  {
    document.getElementById('p'+id).value = wartosc
  }
  
  function znacz_pw(id, wartosc)
  {
    tabl = $$('input[name~="odp['+id+'][]"]');
    var wart=""
    for (var index = 0; index < tabl.length; ++index) 
	{
      var item = tabl[index];
      if(item.checked == true)
        { wart = wart + item.value + ","; }
    }
    document.getElementById('p'+id).value = wart;
  }
function pop(plik,w,h)
{
aw=800;
ah=600;
okno = null;
if(window.screen)
{
aw = screen.availWidth;
ah = screen.availHeight;
}
dane="width="+w+",height="+h+",left="
+(aw-w)/2+",top="
+(ah-h)/2
+",toolbar=no,location=no,directories=no,"
+"status=no,menubar=no,"
+"scrollbars=yes,resizable=no";
okno=window.open(plik,'pop',dane);
if (window.focus) {okno.focus()}

}

function pop2(plik,w,h)
{
aw=800;
ah=600;
okno = null;
if(window.screen)
{
aw = screen.availWidth;
ah = screen.availHeight;
}
dane="width="+w+",height="+h+",left="
+(aw-w)/2+",top="
+(ah-h)/2
+",toolbar=no,location=no,directories=no,"
+"status=no,menubar=no,"
+"scrollbars=yes,resizable=yes";
okno=window.open(plik,'pop',dane);
}


function enable_text_desc(pytanie, wariant)
{
  pid = "set_"+pytanie
  tm = $(pid) 
  lista = tm.childElements(); 
  lista.each(function(e) 
  { 
    if(e.type=='text') 
    {  
      if(e.id!="odp_wariant_desc_"+wariant)
       {
       e.disabled=true
       e.value=""
       } 
       else 
	   {
       e.disabled=false
       } 
      
    }
  }
);
}

function enable_text_desc_checkbox(pytanie, wariant)
{
  pid = "set_"+pytanie
  tm = $(pid) 
  lista = tm.childElements(); 
  lista.each(function(e) 
  { 
    if(e.type=='text') 
    {  
      if(e.id!="odp_wariant_desc_"+wariant)
       {
  
       } 
       else 
       {    if($('odp_'+pytanie+'_'+wariant).checked)
             {e.disabled=false}
             else
             {
                e.disabled=true
                e.value=""
             }
       } 

    }
  }
);
}

function only_number(x)
{
  szablon = new Array("[0-9]");
  tekst="";
  for (i=0;i<x.value.length;i++) {
    re = new RegExp(szablon[0]);
    if (x.value.charAt(i).match(re)) {
      tekst += x.value.charAt(i);
    }
  }
  x.value=tekst;
}

function zip_code_validation(x) 
{
  szablon = new Array("[0-9]","[0-9]","[-]","[0-9]","[0-9]","[0-9]");
  tekst="";
  for (i=0;i<szablon.length;i++) 
  {
    re = new RegExp(szablon[i]);
    if (x.value.charAt(i).match(re)) 
	{
      tekst += x.value.charAt(i);
    }
  }
  x.value=tekst;
}

function unhide(divID) {
  var item = document.getElementById(divID);
  if (item) {
    item.className=(item.className=='hidden')?'unhidden':'hidden';
  }
}

function showall() {
  $$('tr([class="hidden"])').each(function(s) {s.className='unhidden';});
}

function change_tab(tab_id, link)
	{
	    $$('a.selected').each(function(s) {
		s.className='';});
		link.className='selected';
	   	
	}