var ile = {};

function trans(source_id, target_id, img) {
    
      if (img == null){
        img = "";
      }
    
      var source = $('#' + source_id );
      var target = $('#' + target_id );
      
      var shadow = $('#' + source_id + '_shadow');
      
      if( !shadow.attr('id') ) {
          $('body').prepend('<div id="'+source.attr('id')+'_shadow" style="display: none; background: #aaa url('+img+') no-repeat center center; border: solid 1px darkgray; position: static; top: 0px; z-index: 100000;">&nbsp;</div>');
          var shadow = $('#'+source.attr('id')+'_shadow');
      }
      
      if( !shadow ) {
          alert('Cannot create the shadow div');
      }
      
      shadow.width(source.css('width')).height(source.css('height')).css('top', source.offset().top).css('left', source.offset().left).css('opacity', 0.7).show();
      shadow.css('position', 'absolute');
      
      shadow.animate( { width: target.innerWidth(), height: target.innerHeight(), top: target.offset().top, left: target.offset().left }, { duration: 500 } )
        .animate( { opacity: 0 }, { duration: 300, complete: function(){shadow.remove();} } );
}




function updateBasketView(count,price,source_div,img,name)
{
    if (img == null){
        img = "";
    }
      
    if (source_div!='')
    {   
        $.scrollTo(0,{ 
            duration:500, 
            onAfter: function(){
                $("#top_basket_items").fadeOut(300,function(){$("#top_basket_items").html(count);$("#top_basket_items").fadeIn(100);});
                $("#top_basket_price").fadeOut(300,function(){$("#top_basket_price").html(parseFloat(price).toFixed(2)+" PLN");$("#top_basket_price").fadeIn(100,function(){
                    if (name!=null)
                    {
                        spawnTip("top_basket_icon",name,1500);
                    }
                });});
            } 
        });    
        trans( source_div, 'top_basket', img );
    } 
    else
    {
        $("#top_basket_items").fadeOut(300,function(){$("#top_basket_items").html(count);$("#top_basket_items").fadeIn(100);});
        $("#top_basket_price").fadeOut(300,function(){$("#top_basket_price").html(parseFloat(price).toFixed(2)+" PLN");$("#top_basket_price").fadeIn(100,function(){
            if (name!=null)
            {
                   spawnTip("top_basket_icon",name,1500);
            }
        });});
    }
}

function spawnTip(target_id,msg,time)
{
    var target = $('#' + target_id );
    var tip = $('#' + target_id + '_tip');
    
    if (time == null){
        time = 800;
    } else {
        time = parseInt(time);
    }
    
    if( !tip.attr('id') ) {
          $('body').prepend('<div id="'+target.attr('id')+'_tip" class="tip_holder" style="display: none;z-index: 100000;opacity:0"><table cellspacing="0" cellpadding="0"><tr><td class="tip" valign="top" align="left">'+msg+'</td><td class="tip_right"> &nbsp;&nbsp;&nbsp;&nbsp; </td></tr></table></div>');
          var tip = $('#'+target.attr('id')+'_tip');
    }
    
    var posy = target.offset().top - tip.innerHeight();
    tip.css('top',  posy+20).css('left', target.offset().left);
    tip.css('position', 'absolute').show();
    
    tip.animate({opacity:1, top:posy},100, function(){
        tip.fadeTo(time,1, function(){
            tip.animate({top:posy-30, opacity:0},400,function(){
                tip.remove();
            });
        });
    });   
}

function is_empty(field,odd)
{
    if (odd == null){
        odd = true;
    }
    
    if ( $("#"+field).length > 0 ) {
        if ($("#"+field).val() == "")
        {
            
            if (ile[field] == null){
                ile[field]=0;
            }
            ile[field]=ile[field]+1;
            if (ile[field]>1) spawnTip(field,"To pole jest wymagane");
            
            if (odd)
            {
                $("#"+field).css("position","relative");
                $("#"+field).animate({left:"-10px"},50).animate({left:"+10px"},50).animate({left:"-10px"},50).animate({left:"+10px"},50).animate({left:"0px"},50);
            } else {
                $("#"+field).css("position","relative");
                $("#"+field).animate({left:"+10px"},50).animate({left:"-10px"},50).animate({left:"+10px"},50).animate({left:"-10px"},50).animate({left:"0px"},50);
            }
            $("#"+field).focus();
            return true;
        }
    }
    return false;
}

function check_and_submit(fields,form)
{
    fields = fields.reverse();
    var ready = true;
    var odd = true;
    
    for (id in fields)
    {
        if ( is_empty(fields[id], odd) )
        {
            ready = false;
            odd = !odd;
        }    
    }
    
    if (ready)
    {
        form.submit();
    }
}


function bookmarksite(title,url){
    if (window.sidebar) // firefox
        window.sidebar.addPanel(title, url, "");
    else if(window.opera && window.print){ // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    }
    else if(document.all)// ie
        window.external.AddFavorite(url, title);
}

var recentHash = "";

function ahah(url, target, type) {
  var h = document.getElementById(target).offsetHeight;
  $("#middle_products").css("min-height",h);
  document.getElementById(target).innerHTML = '<div id=loading></div>';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target, type);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function process_paginator()
{
    $("a[id^=paginator_]").click(function(){
        var temp = $(this).attr("id").split('_');
        var id = temp[temp.length - 1];
        load("inner_"+$(this).attr("href").substr(1), "middle_products","cat");
        window.location.hash = $(this).attr("href");
        recentHash = window.location.hash;
        $.scrollTo(0,500);
    });
}

function process_path()
{
    $("a[id^=path_]").click(function(){
        var temp = $(this).attr("id").split('_');
        var id = temp[temp.length - 1];
        $("#tree").dynatree("getActiveNode").deactivate();
        $("#tree").dynatree("getTree").activateKey("cat_"+id);
        recentHash = window.location.hash;
        $.scrollTo(0,500);
    });
}

function ahahDone(url, target, type) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      $("#middle_products").fadeOut(0);
      document.getElementById(target).innerHTML = req.responseText;
      $("#middle_products").css("min-height","0");
      $("#middle_products").fadeIn("fast");
      
      if (type=="cat")
      {
        document.title = document.getElementById("categoryPath").title;
        process_paginator();
        process_path();
      }
      
      if (type=="prod")
      {
        document.title = document.getElementById("categoryPath").title;
        process_path();
      }
      
    } else {
      document.getElementById(target).innerHTML="<b>AJAX Error: "+ req.status + " " +req.statusText + "</b><br />DEBUG: While loading: "+url+"<br/><br />Please contact your webmaster.";
    }
  }
}

function load(name, div, type) {
	ahah(name, div, type);
	return false;
}

function parseURL()
{
    if (window.location.hash==recentHash) {
       return; // Nothing's changed since last polled.
     }
     recentHash = window.location.hash;

    var hash = window.location.hash.substring(1); 
    var re = new RegExp("(.*)/(\\d+),(\\d+),(.*)");
    var m = re.exec(hash);
    if (m != null) {
        if (m.length>3)
        {
            var reminder = m[4];
            window.openCat = null;
            window.openProd = null;
            window.openPage = null;
            window.reminder = reminder;
            if (m[1]=="cat")
            {
                if ($("#tree").dynatree("getTree")!=null) // tree is already generated
                {
                    $("#tree").dynatree("getTree").activateKey("cat_"+m[2]); //activate appropriate key in the tree
                    load("inner_cat/"+m[2]+","+m[3]+",", "middle_products","cat");
                    window.location.hash = "cat/"+m[2]+","+m[3]+","+reminder;
                } else { // no tree yet - pass arg for tree creation
                    window.openCat = m[2];
                    if (m[3]!=1) // page is other than start
                    {
                        window.openPage = m[3];
                    }
                }
            }
            if (m[1]=="prod")
            {
                if ($("#tree").dynatree("getTree")!=null) // tree is already generated
                {
                    $("#tree").dynatree("getTree").activateKey("cat_"+m[2]); //activate appropriate key in the tree
                    load("prod/"+m[2]+","+m[3]+",", "middle_products","prod");
                    window.location.hash = "prod/"+m[2]+","+m[3]+","+reminder;
                    recentHash = window.location.hash;
                } else { // no tree yet - pass arg for tree creation
                    window.openCat = m[2];
                    window.openProd = m[3];
                }              
            }
        }
    } 
}
