$('html').addClass('js');

$(document).ready(function() {
	$('.lightbox').lightBox();
});

$(document).ready(function() {
	if ( $('ul#catalog-download li').length == 0 ) { $('ul#catalog-download').hide(); }
	$('#img-gallery span.plusIcon').click(function() {
		$('#img-gallery a.lightbox').click();
	});
});

$(function(){
  
  //*** Emulate CSS :after and content for IE6-7 for printing ***/
  if(typeof document.body.style.content === 'undefined') {
    if (window.onbeforeprint !== undefined) {
      window.onbeforeprint = ShowLinks;
      window.onafterprint = HideLinks;
    }
    function ShowLinks() {
      $("#content-main a").each(function() {             
        $(this).data("linkText", $(this).text());
        $(this).append(" (http://www.crom.hr/" + $(this).attr("href") + ")");                
      });
    }
    function HideLinks() {
      $("#content-main a").each(function() {
        $(this).text($(this).data("linkText"));
      });
    }
  }

  //*** Fancybox ***/
/*  $('#img-gallery > a').fancybox();
*/  
  //*** Print control ***/
  $('#page-controls').prepend('<li class="first"><a title="Ispis trenutne stranice">Ispis</a></li>');
  $('#page-controls li:first-child a').click(function(){ window.print(); });
  
  //*** Show all select ***/
  $('#select-show-all option').click(function(){
    if ( $(this).val() === '0' ) {
      location.href = $(this).closest('form').attr('action');
    } else {
      location.href = $(this).closest('form').attr('action')+'/'+$(this).val();
    }
  });
  
  //*** Category selector ***/
  var subCat = '#category-selector #sub-categories ul';
  scrollStyling($(subCat));
  $('#sub-categories-close').click(function() { subCatLastRemove($(this)); });
  $(subCat).find('li a').live('click',function(e){
    if ( !$(this).is('[rel=link]') ) {
      $(this).addClass('loading').parent().addClass('active');
      $(this).parents('.jScrollPaneContainer').nextAll().remove();
      $.ajax({
        url: $(this).attr('href'),
        success: function(data) {
          $(subCat).find('li a').removeClass('loading');
          $(data).appendTo('#category-selector #sub-categories');
          $(subCat).last().show(1,function(){ scrollStyling($(this));})
          if ( $('#sub-categories-close').length===0 ) {
            $('<a id="sub-categories-close">Zatvori</a>').click(function() {
              subCatLastRemove($(this));
            }).appendTo('#category-selector');       
          }
        }
      });
      e.preventDefault();
    }
  });
  function scrollStyling(subCatEl) {
    subCatEl.each(function(){
      if ( !$(this).parent().is('.jScrollPaneContainer') ) {
        $(this).jScrollPane({
          scrollbarMargin:0,
          scrollbarWidth:12,
          dragMaxHeight:63,
          showArrows: true
        }).children(':first-child').addClass('first');
        $('<span class="sep" />').click(function(){
          $(this).siblings('ul').find('li:first-child a').trigger('click');
        }).hover(function(){
          $(this).siblings('ul').find('li:first-child a').toggleClass('hover');
        }).insertAfter($(this));
      }
    });
  }
  function subCatLastRemove(subCatLastRemoveEl){ 
    $('#sub-categories').children(':last-child').remove();
    if ( $('#sub-categories').children().length===1 ) { subCatLastRemoveEl.remove(); }
  }
  
  //*** Contacts category dropdown
  $('#contacts-cat').wrap('<div id="contacts-cat-wrap"></div>').before('<em></em>');
  var contactsCatVis = 'hidden';
  $('#contacts-cat-wrap em').html($('#current-contacts-cat').text()).click(function(){
   if($(this).next().is(':hidden')) { $(this).next().show(1,function(){ contactsCatVis = 'visible'; }); }
   else { $(this).next().hide(1,function(){ contactsCatVis = 'hidden'; }); }
  });
  
  $().click(function(){ if ( contactsCatVis == 'visible' ) { $('#contacts-cat').hide(1,function(){ contactsCatVis = 'hidden' }); } });
  
  //*** Product image gallery ***/
  $('#img-gallery ul li:first-child').addClass('active');
  $('#img-gallery ul a').click(function(){
    var imgLink = $(this).attr('href');
    var imgSmall = $(this).attr('rel');
    var imgTitle = $(this).attr('title');
    var imgBig = $('#img-gallery img');
    $(this).parent().addClass('active').siblings().removeClass('active');
    $('#img-gallery > a').addClass('loading');
    if ( imgBig.attr('src') !== imgSmall ) {   
      imgBig.animate({ opacity: 0 }, function(){
        var img = new Image();
        $(img).load(function(){   
          $(this).css({opacity: 0});
          $('#img-gallery > a').removeClass('loading').html(this);
          $(this).animate({opacity: 1}).parent().attr({ href: imgLink, title: imgTitle });
        }).error(function(){}).attr('src', imgSmall);
      });
    }
    return false;
  });
  
  //*** Special offer carousel ***/
    var scrollAmount=179;
    var scrollNum=2;
    var scrollEnd=$("#so-carousel .picScroller div a").length;
    
    $("#so-carousel .picScroller div a:eq(1)").addClass("on");
    $("#so-carousel .show-all").before('<a class="back" title="Prethodni proizvod">Prethodni proizvod</a><a class="next" title="Sljedeći proizvod">Sljedeći proizvod</a>');
    $("#so-carousel .picScroller div").width('9999px');
    
    $("#so-carousel .back").click(function(){
        if ( scrollNum==1 || $(".picScroller .scroller").is(":animated") || $(".picScroller div a").is(":animated") || $(".picScroller div img").is(":animated") || $("#so-carousel ul li").is(":animated") ){ return false; }
        $("#so-carousel .next").removeClass("disabled");
        scrollNum = scrollNum-1;
        var activeElement = $(".picScroller div .on"); 
        
        $("#so-carousel ul .on").fadeOut("fast",function(){
            $(this).removeClass("on").prev().fadeIn().addClass("on");
        });
        activeElement.animate({marginTop: "15px"});
        activeElement.find(".so-carousel-box").animate({width: "169px" });
        activeElement.find(".so-carousel-pic").animate({width: "153px" });
        activeElement.prev("a").animate({marginTop: "0px"});
        activeElement.prev("a").find(".so-carousel-box").animate({width: "205px" });
        activeElement.prev("a").find(".so-carousel-pic").animate({width: "185px" });

        $(".picScroller div").animate({marginLeft: "-"+(-parseFloat($(".picScroller div").css("margin-left"))-scrollAmount)+"px"},function(){
            activeElement.removeClass("on").prev("a").addClass("on");
        });
        if(scrollNum==1){ $("#so-carousel .back").addClass("disabled"); }
    });
    $("#so-carousel .next").click(function(){
        if ( scrollNum==scrollEnd || $(".picScroller .scroller").is(":animated") || $(".picScroller div a").is(":animated") || $(".picScroller div img").is(":animated") || $("#so-carousel ul li").is(":animated") ){ return false; }
        $("#so-carousel .back").removeClass("disabled");
        scrollNum = scrollNum+1;
        var activeElement = $(".picScroller div .on"); 
        
        $("#so-carousel ul .on").fadeOut(function(){
            $(this).removeClass("on").next().fadeIn().addClass("on");
        });

        activeElement.animate({marginTop: "15px"});
        activeElement.find(".so-carousel-box").animate({width: "169px" });
        activeElement.find(".so-carousel-pic").animate({width: "153px" });
        activeElement.next("a").animate({marginTop: "0px"});
        activeElement.next("a").find(".so-carousel-box").animate({width: "205px" });
        activeElement.next("a").find(".so-carousel-pic").animate({width: "185px" });

        $(".picScroller div").animate({marginLeft: "-"+(-parseFloat($(".picScroller div").css("margin-left"))+scrollAmount)+"px"},function(){
            activeElement.removeClass("on").next("a").addClass("on");
        });
        if(scrollNum==scrollEnd){ $("#so-carousel .next").addClass("disabled"); }        
    });
    
    //*** Bigger link ***/
    $('#new-in-offer.home-box li, #special-offer-pick li').biggerlink({hoverclass:'hover'});
    
    //*** GMap ***/
    if ( $("#gmap").html()!=null ){
      DGoogleMap2.setOption( 'zoom', 13 );
      DGoogleMap2.setOption( 'center', new GLatLng(45.784723,16.029264) );
      DGoogleMap2.mapDefaultUI.zoom.scrollwheel=false;
      DGoogleMap2.mapDefaultUI.controls['overviewmapcontrol'] = false;
      var s = DGoogleMap2.displayMap("#gmap");
      DGoogleMap2.displayMarkers();
    }
});

//PRODUCT POPUP
$(document).ready(function() {
	$('.openPopup, .popupProduct button[type=submit]').live('click', function(e){
		e.preventDefault();
		
		var _url = $('a.openPopup').attr('rel');
		
		$.ajax({
			url: _url,
			type: ( $(this).is('button[type=submit]') ) ? 'POST' : 'GET',
			data: ( $(this).is('button[type=submit]') ) ? $(this).closest('form').serialize() : null,
			dataType: 'html',
			success: function(data){
				$('#popup_form_wrapper').remove();
				openPopup(data, 'popupProduct');
			}
		});
		
	});
});

//OPEN POPUP
function openPopup(popupContent, popupClass) {
	$('body').append('<div id="popup_form_wrapper"><div id="popup_form_overlay"></div><div id="popup_form" class="' + popupClass + '"><div class="close"></div><div id="popup_form_inner">' + popupContent + '</div></div></div>');
	var overlayEl = $('#popup_form_overlay');
	overlayEl.css({ height:$(document).height(), width:$(window).width() }).show();

	$('#popup_form_wrapper .close, #popup_form_wrapper button[type=reset], #popup_form_overlay').click(function(e){
		e.preventDefault();
		$('#popup_form_wrapper').remove();
	});
	$('#popup_form_wrapper #popup_form').css('top', $(window).scrollTop() + 80 );
	$('#popup_form_wrapper').show();
}

//CLEAR-DEFAULT TEXT
$(document).ready(function() {
	$('input.clear-default, textarea.clear-default').each(function() {
		var defaultTitle = $(this).attr('title');
		if ($(this).attr('value') == defaultTitle) {
			$(this).css({'fontStyle':'italic', 'fontWeight':'normal', 'color':'#7c7c7c'});
		}
		if ($(this).attr('value') == '') {
			$(this).attr('value', defaultTitle).css({'fontStyle':'italic', 'fontWeight':'normal', 'color':'#7c7c7c'});
		}
		$(this).focus(function() {
			if ($(this).attr('value') == defaultTitle) {
				$(this).attr('value', '').css({'fontStyle':'normal', 'fontWeight':'normal', 'color':'#333333'});
			}
		});
		$(this).blur(function() {
			if ($(this).attr('value') == '') {
				$(this).attr('value', defaultTitle).css({'fontStyle':'italic', 'fontWeight':'normal', 'color':'#7c7c7c'});
			}
		});
	});
	
	$('input.clear-default, textarea.clear-default').closest('form').submit(function() {
		$(this).find('input[type=text][title], textarea[title]').each(function() {
			var defaultTitle = $(this).attr('title');
			if ($(this).attr('value') == defaultTitle) {
				$(this).attr('value', '');
			}
		});
	});
});

/**
* GOOGLE ANALYTICS FUNKCIJE
*/
var pageTracker_trackEvent_Kontakt_Poslano = function(){
	_gaq.push(['_trackEvent', 'Kontakt-obrazac', 'Kontakt-obrazac-Poslano']);
	if( typeof console != 'undefined' && console ) console.log("_trackEvent( 'Kontakt-obrazac', 'Kontakt-obrazac-Poslano' )");
};
var pageTracker_trackEvent_ProizvodUpit_Poslano = function( event, proizvod ){ 
	proizvod = ( typeof event != 'undefined' && typeof event.data != 'undefined' && typeof event.data.proizvod != 'undefined' ) ? event.data.proizvod : proizvod;
	_gaq.push(['_trackEvent', 'ProizvodUpit', 'ProizvodUpit-Poslano', proizvod]);
	if( typeof console != 'undefined' && console ) console.log("_trackEvent( 'ProizvodUpit', 'ProizvodUpit-Poslano', "+proizvod+" )");
};
var pageTracker_trackEvent_PosebnaPonudaUpit_Poslano = function( event, proizvod ){ 
	proizvod = ( typeof event != 'undefined' && typeof event.data != 'undefined' && typeof event.data.proizvod != 'undefined' ) ? event.data.proizvod : proizvod;
	_gaq.push(['_trackEvent', 'PosebnaPonudaUpit', 'PosebnaPonudaUpit-Poslano', proizvod]);
	if( typeof console != 'undefined' && console ) console.log("_trackEvent( 'PosebnaPonudaUpit', 'PosebnaPonudaUpit-Poslano', "+proizvod+" )");
};
var pageTracker_trackEvent_IzdvojenoUpit_Poslano = function( event, proizvod ){ 
	proizvod = ( typeof event != 'undefined' && typeof event.data != 'undefined' && typeof event.data.proizvod != 'undefined' ) ? event.data.proizvod : proizvod;
	_gaq.push(['_trackEvent', 'IzdvojenoUpit', 'IzdvojenoUpit-Poslano', proizvod]);
	if( typeof console != 'undefined' && console ) console.log("_trackEvent( 'IzdvojenoUpit', 'IzdvojenoUpit-Poslano', "+proizvod+" )");
};
