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

var chatWindow;
var chatTimer;
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 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 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';
	   	
	}
function writeBannerSkorut() {
   document.write('<a href="http://www.skorut.com.pl/" target="_blank" title="SYSTEMY SOLARNE"><img src="/images/banners/baner_skorut.jpg" width="625" height="55" alt="SYSTEMY SOLARNE" /></a>');
}   
function writeBannerConvector() {
   document.write('<a href="http://www.convector.pl/" target="_blank" title="Convector - grzejniki konwekcyjne oraz grzejniki miedziano aluminiowe typu konwektor"><img src="/images/banners/convector.gif" width="625" height="55" alt="Convector - grzejniki konwekcyjne oraz grzejniki miedziano aluminiowe typu konwektor" /></a>');
}   
function writedoradcaprojektowy() {
   document.write('<a href="http://doradcaprojektowy.archon.pl/client.php?locale=pl&amp;style=simplicity" target="_blank" onclick="if(navigator.userAgent.toLowerCase().indexOf(\'opera\') != -1 &amp;&amp; window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open(\'http://doradcaprojektowy.archon.pl/client.php?locale=pl&amp;style=simplicity&amp;url=\'+escape(document.location.href)+\'&amp;referrer=\'+escape(document.referrer), \'webim\', \'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1\');this.newWindow.focus();this.newWindow.opener=window;return false;"><img src="http://doradcaprojektowy.archon.pl/button.php?image=webim&amp;lang=pl" border="0" width="169" height="61" alt=""/></a>');
}

function writedoradcaprojektowy2() {
   document.write('<a href="http://doradcaprojektowy.archon.pl/client.php?locale=pl&amp;style=simplicity" target="_blank" onclick="if(navigator.userAgent.toLowerCase().indexOf(\'opera\') != -1 &amp;&amp; window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open(\'http://doradcaprojektowy.archon.pl/client.php?locale=pl&amp;style=simplicity&amp;url=\'+escape(document.location.href)+\'&amp;referrer=\'+escape(document.referrer), \'webim\', \'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1\');chatWindow=this.newWindow;this.newWindow.focus();this.newWindow.opener=window;chatTimer=window.setInterval(\'checkChatWindow()\', 1000);return false;"><img src="http://doradcaprojektowy.archon.pl/button.php?image=webim&amp;lang=pl" border="0" width="169" height="61" alt=""/></a>');
}

function checkChatWindow() {
	if(chatWindow.closed) 
		{  
			clearInterval(chatTimer);
			win = window.open('http://test.archon.pl/survey/chat', 'Badanie','width=800,height=600,status=0,toolbar=0');
		}
}

function writefundacjalink() {
   document.write('<a href="http://www.rodzinazastepcza.org.pl" title="www.rodzinazastepcza.org.pl" target="_blank" style="color:#0066CC;"><b style="color:#0066CC;">www.rodzinazastepcza.org.pl</b></a> - strona internetowa fundacji.');
}  

function write_opineo() {
   document.write('<a href="http://www.opineo.pl/opinie/archon-pl" onclick="_gaq.push([\'_trackEvent\', \'Click-count\', \'zewnetrzne\', \'opineo\']);"><img src="http://static.archon.pl/certyfikat3.jpg" alt="Opinie o ARCHON+ Biuro Projektów na Opineo.pl" title="Opinie o ARCHON+ Biuro Projektów na Opineo.pl"></a>');
} 


function write_facebook() {
   document.write('<a name="fb_share" type="icon_link" href="http://www.facebook.com/sharer.php">Udostępnij</a><script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>');
}

function write_becomefan() {
   document.write('<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/pl_PL"></script><script type="text/javascript">FB.init("45ada8508d4b36e83c4b60e7834f9eee");</script><fb:fan profile_id="189024982400" stream="" connections=""></fb:fan><div style="font-size:8px; padding-left:10px" id="facebookfan"> </div>');
} 

// verifies only a number was typed into the form element
    function numbersonly(e){
        var unicode=e.charCode? e.charCode : e.keyCode;
        // if (unicode!=8||unicode!=9)
        if (unicode<8||unicode>9)
            {
            if (unicode<48||unicode>57) //if not a number
            return false //disable key press
        }
    }
// otwiera okienko czatu i okienko z ankieta badania satysfakcji
function openMibew() {
		window.open('http://archon.pl/survey/chat', 'badanie', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=680,resizable=1');
		return window.open('http://doradcaprojektowy.archon.pl/client.php?locale=pl&style=simplicity&url='+escape(document.location.href)+'&referrer='+escape(document.referrer), 'webim', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1');
	}
