var dialog = $('<DIV id="ajaxDialog" title="" class="ajaxDialog">'+
	                '<object class="loaderFlash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  codeBase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0" height="400" width="100%" align="middle">'+
		                '<param VALUE="24553" NAME="_cx"/>'+
		                '<param VALUE="1376" NAME="_cy"/>'+
		                '<param VALUE="/site/core/images/loading.swf" NAME="Movie"/>'+
		                '<param VALUE="/site/core/images/loading.swf" NAME="Src"/> '+
		                '<param VALUE="Transparent" NAME="WMode"/>'+
		                '<param VALUE="High" NAME="Quality"/>'+
		                '<param VALUE="-1" NAME="Menu"/>'+
		                '<param VALUE="ShowAll" NAME="Scale"/>'+
		                '<embed wmode="transparent"  height="400" width="100%" type="application/x-shockwave-flash" src="/site/core/images/loading.swf" scale="showall" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" menu="false"/></object>'+
	              '</DIV>');

//var dialog = $('<DIV id="ajaxDialog" title="" class="ajaxDialog"></DIV>');

var fixLength = 0;
var actionAjax = 'add_product';
var pos = -1;
var	lowerIdNew = null;

$(document).ready(function(){    
    $('.ssIntervalsDirect:first').css('display','block');
    $('.ssAjaxLine > .ssLineContent .ssIntervals').each(function(){
        $(this).find('.ssIntervalsDirect:first').show();
    });
       
    /* Select first items */
    $('.ssContainers,.ssIntervals,.ssIntervalsDirect').each(function(){
	       $(this).find('.ssItem:first').addClass('itemSelected');
    });    
});


function selectSsItem(){	        
    $('*[ssLine]').click(function(e){ 		  
        $('.ssFirstLine').css('display','none');        
		      var parent = $(this).parents('*[SS_LINE]');	
		      $('.ssFirstLine,.ssAjaxLine',$(parent)).css('display','block');
		      $('.ssLineBot',$(parent)).css('display','block');
		      $('*[ssLine]').removeClass('lineSelected');
		      $('*[lineContent]').hide().css('visibility','hidden');		
		      $('img.picLine').css('display','block');
		      $('img.picLineSelected').css('display','none');
		      $('img.picLine',this).css('display','none');
		      $('img.picLineSelected',this).css('display','block');
		      $(this).addClass('lineSelected');
		      $('*[lineContent='+$(this).attr('ssLine')+']').show().css('visibility','visible');
		      //IE6 fix - begin
		      $('.ssLineBot').css('margin-top','0px');
			/*	if($(this).attr('ssLine') == 44 && navigator.userAgent.indexOf('MSIE') != -1 && navigator.userAgent.indexOf('6.0;') != -1)
            $('.ssSecondLine > .ssLineBot').css('margin-top','-17px');*/
        //IE6 fix - end 
		      trackEvent($(this).attr('ssLine'));
		      $('.ssIntervalsDirect').hide();        
		      $('*[lineContent='+$(this).attr('ssLine')+'] .ssIntervalsDirect:first').show();        
    });
	
	
	  //Only for Direct
   $('.ssContainersDirect > *[ssItem]:first').addClass('itemSelected');
	  $('.ssContainersDirect > *[ssItem]').click(function(e){														
	  var directUperId = $(this).attr('upperId');
	  $('*[directUper]').css('display','none');
	  var blockDirectUper = $('*[directUper='+directUperId+']');
	  $(blockDirectUper).css('display','block');
	  lowerIdNew = $('.itemSelected',blockDirectUper).attr('lowerId');
	});

	
$('*[ssItem]').click(function(e){        
    $('.orderNotChosen').css('display','none');
		  var price = 0;
		  var self = this;
		  self = $(self);		  
		  var entity = (!isNaN(self.attr('upperId')))? 'upper':'lower';
		  var entityInstead = (!isNaN(self.attr('upperId')))? 'lower':'upper';		  
		  try{
			     var parent = self.parents('*[lineContent]');
			     var idLine = parent.attr('lineContent');
				    for(var i = 0; i < sitaShops.WasteStream.length-fixLength; i++){
				        var stream = sitaShops.WasteStream[i];
				        if(stream.id==idLine){
					           trackSubSelection(self, stream);
					           for(var j = 0; j < stream.prices.length-fixLength; j++){
						              var entityId = self.attr(entity+'Id'); 
						              $(stream).attr(entity+'Entity',entityId);
						              //Only for Direct
							             if(lowerIdNew!=null && $(stream).attr('type')=='DIRECT') $(stream).attr('lowerEntity',lowerIdNew);
						              //
						                  if($(stream.prices[j]).attr(entity+'EntityId')==entityId && 
							                     $(stream.prices[j]).attr(entityInstead+'EntityId')==$(stream).attr(entityInstead+'Entity') &&
							                     (stream.upperEntity!=null && stream.lowerEntity!=null))
						                      { 
							                        price = stream.prices[j].price;
							                        stream.price = price;
							                        stream.priceItemId = stream.prices[j].id;
							                        break;
						                      }
					                   }					
					               break;
				            }
			         }
		  }catch (e){}
  		
  		$('.ssItem',$(this).parent()).removeClass('itemSelected');
		  $(this).addClass('itemSelected');		  
		  		  
		  $('.sumPrice > span').text(price);		  
		  if(stream.priceItemId!=null){
			     $('.orderBtn .submit',parent).attr('priceItemId',stream.priceItemId);		
		  }		  
	});
}

function directOrderLink(id) {
	$("body").append('<form method="post" action="uw_producten_'+lang+'.html" id="directOrderLink" name="directOrderLink"><input type="hidden" name="action" value="add_product"/><input type="hidden" name="type" value="directOrderLink"/><input type="hidden" id="id_product_id" name="product_id"/></form>');
	$('#id_product_id').val(id);
	document.forms['directOrderLink'].submit();
}

function orderProduct(){		   
	   $('*[priceItemId]').click(function(e){		      
		      try{
			         if($(this).attr('priceItemId')!=0){
				            url = 'uw_producten_'+lang+'.html';
				            if(actionAjax=='add_product'){
					               $(dialog).dialog({
						                  bgiframe: true,
						                  width: 740,
						                  height: 700,
						                  position: [160,180],
						                  modal: true,
						                  dialogClass: 'popupBlock',
						                  open: function(){var dialog = this},				
						                  close: function() {}
					               });	
					
					               params = '?command=edit-cart-command-xml&action=add_product&product_id='+$(this).attr('priceItemId');
					               $.get(url+params, function(data) {
				   		               window.location=url;				   		
					               });
				            }else{
					               position  = (pos>-1)?'&position='+pos:'';
					               params = '?command=edit-cart-command&action='+actionAjax+position+'&product_id='+$(this).attr('priceItemId');				
					               $.get(url+params, function(data) {
						                  $('#pm_items').html(data);						
						                  createDialogContract();    
						                  closeDialogUI()
					               });
				            }
			         }else{
				            $('.orderNotChosen',$(this).parent()).css('display','block');
			         }
		      }catch (e){}
    })						   
    
	   $('*[packageId]').click(function(e){        
        try{
			         if($(this).attr('packageId')!=null){
			             $(dialog).dialog({
					               bgiframe: true,
					               width: 740,
					               height: 700,
					               position: [160,180],
					               modal: true,
					               dialogClass: 'popupBlock',
					               open: function(){var dialog = this},				
					               close: function() {}
				            });	
				            url = 'uw_producten_'+lang+'.html';
				            params = '?command=edit-cart-command-xml&action=add_package&id='+$(this).attr('packageId');
				            $.get(url+params, function(data) {window.location=url;});
			         }
		      }catch (e){}
	   })						   
}


function toolTip() {         
    var parentTooltip =  "";
	   var objTip = "";	
	   var paddingLeft= ($(document).width()-$('.container').width())/2;
	   paddingLeft = (paddingLeft>0)?paddingLeft:0;
	   var x = 210;		
	   
	   $('*[toolTip]').mouseover(function(e) {									  
		      var tip = $(this).attr('title');
		      paddingLeft= ($(document).width()-$('.container').width())/2;
		      parentTooltip =  $(this).parents('*[line=SS_SECOND_LINE]');
		      var posY = (parentTooltip.length>0)?485:260;		
		      var posX = e.pageX-paddingLeft-x;	
		      $(this).attr('title','');		
		      objTip = $('.toolTipTable',$(this));
		      objTip.css('top', e.pageY-posY);
		      objTip.css('left', posX);
		      objTip.css('display','block');		      
	   }).mousemove(function(e) {		   
		      var posY = (parentTooltip.length>0)?485:260;
		      var posX = e.pageX-paddingLeft-x;	
		      try{
		        objTip.css('top', e.pageY-posY);
		        objTip.css('left', posX);				        
		      }catch(e){
			         objTip = $('.toolTipTable',$(this));
		      }
	   }).mouseout(function() {	   
		      objTip.css('display','none');		
	   });
}

function toolTipXY(x,y) {
	   var parentTooltip =  "";
	   var objTip = "";
	   var paddingLeft= ($(document).width()-$('.container').width())/2;
	   paddingLeft = (paddingLeft>0)?paddingLeft:0;
	   
	   $('*[toolTip]').mouseover(function(e) {									  		      
		      var tip = $(this).attr('title');
		      paddingLeft= ($(document).width()-$('.container').width())/2;
		      parentTooltip =  $(this).parents('*[line=SS_SECOND_LINE]');
		      $(this).attr('title','');		
		      objTip = $('.toolTipTable',$(this));
		      objTip.css('top', e.pageY-y);
		      var posX = e.pageX-paddingLeft-x;	
		      objTip.css('left', posX);		      
		      objTip.css('display','block');
	   }).mousemove(function(e) {			      
		      try{
			         objTip.css('top', e.pageY -y);
			         var posX = e.pageX-paddingLeft-x;	
			         objTip.css('left', posX);			         			         
		      }catch(e){
			         objTip = $('.toolTipTable',$(this));
		      }
	   }).mouseout(function() {		      
		      objTip.css('display','none');		
	   });
}

function addStream(action, position, parentEntityId, priceItemId){		   
	   $(dialog).dialog({
			         bgiframe: true,
			         width: 740,
			         height: 700,
			         position: ['center',100],
			         modal: true,
			         dialogClass: 'popupBlock',			
			     open: function(){								        
				        var dialog = this;
				        var param = '?command=edit-cart-command&action=browse';				        
				        if (parentEntityId > 0)	param = param +'&parentEntityId='+parentEntityId+'&priceItemId='+priceItemId;				            				            
				            $.get(param, function(data, textStatus){					               					               					               
					               $('.loaderFlash', dialog).remove();
					               $('#ajaxDialog').html(data);                    					               						              
						              createDialogContract();    
					               actionAjax = action;
					               pos = position;						                  		                  
		                  $('.lines .line:first').addClass('lineSelected');
		                  $('.ssIntervals,.ssIntervalsDirect,.ssContainers').each(function(){	                       	                       
	                       if($(this).find('.itemSelected').length == 0)
	                           $(this).find('.ssItem:first').addClass('itemSelected');
                    });		   
		                  $('.lineSelected img.picLine').hide();
                    $('.lineSelected img.picLineSelected').show();
		                  $('.ssIntervals').each(function(){
                        $(this).find('.ssIntervalsDirect:first').show();
                    });            
                    
                    //var buttonConteiner = $('.ui-dialog-titlebar-close').parent();                    
                    //$(buttonConteiner).prependTo('.closeDisplay'); 
                    //$(buttonConteiner).clone().addClass('submitExit').prependTo('.ssAjaxLine .orderBlock .orderBtn > .submit');
                    //$(buttonConteiner).addClass('submitExit').prependTo('.ssAjaxLine .orderBlock .orderBtn > .submit');
                                        
                    //var submitWidth = $('.ssAjaxLine .orderBlock .orderBtn > .submit').attr('clientWidth')+ 15;
                    //$('.submitExit').attr('style', 'width:'+ submitWidth +'px !important; height: 30px !important; top:2px !important;');
                    
                    
                    $(".closeDisplay").click(function(event) {                                
                            /*
                            var t = event.isPropagationStopped();
                            event.stopImmediatePropagation();
                            */
                            closeDialogUI();	 	   
                            toolTipXY(195,165);
                            /*
	                           $('.ssFirstLine').hide();
	                           $('img.picLine').show();;
	                           $('img.picLineSelected').hide();
	                           $('*[ssLine]').removeClass('lineSelected');
	                           $('.ssIntervalsDirect').hide();        
	                           toolTipXY(195,165);
	                           $('#ajaxDialog').remove();
	                           */
                    }); 
                })
			         },				
			     close: function() {
				        $(this).remove();				        
				        toolTipXY(195,165);
			     }
	   });	
	   return false;	   
}

function closeDialog(n){		        
    closeDialogUI();	 	   
    /* HOME PAGE*/ 
    
    closeDialogUI();	 	   
	   $('.ssFirstLine').hide();
	   $('img.picLine').show();;
	   $('img.picLineSelected').hide();
	   $('*[ssLine]').removeClass('lineSelected');
	   $('.ssIntervalsDirect').hide();        
	   toolTipXY(195,165);
	   $('#ajaxDialog').remove();
	   
}

function removeItem(position){				
	   url = 'uw_producten_'+lang+'.html';
	   params = '?command=edit-cart-command&action=delete&position='+position;
	   $.get(url+params, function(data) {
		      $('#pm_items').html(data);			
		      createDialogContract();    
		      closeDialogUI()
		  });
}

function closeDialogUI(){
    $(".ui-widget-overlay").each(function() {$(this).remove();});
    $(".ui-dialog").each(function() {$(this).remove();});
}

function sendExtraOrder(){
	   $('form').each(function() {
		      if ($(this).attr('form_id') > 0 && validate(this)) {
			         $(this).attr('onsubmit', '');
			         var form = this;
			         $.ajax({
				            type: "POST",
            				url: "/extra_empting?action=validateCaptcha&captcha_input="+$(this).find('input[type=text]:last').val(),
				            dataType: "html",
            				success: function(html, stat) {					               
					               if ($(html).html() == 'true'){
						                  form.submit();
					               } else{
						                  refreshCaptcha(form);						
					               }
			             },
				            error: function(html, stat) { }
			         });
		      }
	   });
}

function refreshCaptcha(form){
	   $(this).find('input[type=text]:last').val("");
	   d = new Date();
	   $(form).find("img:last").attr('src', '/captcha.jpg?'+d.getTime());
}

function fillWasteStreamDropDown(firstOption){
	   $.ajax({
        type: "POST",
        url: "/extra_empting?action=getExtraEmptingWasteStreams",
        dataType: "html",
        success: function(html, stat) {
			         $('form').each(function() {
				            if ($(this).attr('form_id') > 0) {
					               drop = $(this).find('select').get(0);
					               $(this).find('select').each(function(){
						                  $(this).attr('sita_drop_down', 'true');
					               });
					               $(this).find("input[type='checkbox']").each(function(){
						                  $(this).attr('sita_checkbox', 'true');
					               });
					               if (drop!= null && drop != 'undefined') {
						                  $(drop).html("<option value='0'>" + firstOption + "</option>" + html);
						                  $(drop).change(function(){fillContainerDropDowns(this)});
						                  $(drop).css('display', 'none');
						                  $(drop).css('display', '');
					               }
				            }
			         });
        },
        error: function(html, stat) { }
    });
}

function fillContainerDropDowns(ws){
	   $('form').each(function() {
		      if ($(this).attr('form_id') > 0){
			     drop = $(this).find('select').get(1);
			     if (drop!= null && drop != 'undefined'){
				        if ($(ws).find('option[selected=true]').attr("entity_id") > 0){
					           $.ajax({
						              type: "POST",
						              url: "/extra_empting?action=getExtraEmptingContainers&id="+$(ws).find('option[selected=true]').attr("entity_id"),
						              dataType: "html",
						              success: function(html, stat) {
						                  $(drop).html(html);
						                  $(drop).css('display', 'none');
						                  $(drop).css('display', '');
					               },
						              error: function(html, stat) { }
					           });
				            }else{
					               $(drop).html("<option value='0'>" + select_container + "</option>");
					               $(drop).css('display', 'none');
					               $(drop).css('display', '');
				            }
			         }
		      }
	   });
}

function trackEvent(entityId){
	   try {
		      var type = '';
		      var entityName = '';
		      for(var i = 0; i < sitaShops.WasteStream.length-fixLength; i++){
			         stream = sitaShops.WasteStream[i];
			         if (stream.id == entityId){
				            entityName = stream.title;
				            type = type_waste_stream;
				            break;
			         }
		      }
		      if (entityName == '' && type == ''){
			         for(var i = 0; i < sitaShops.Package.length-fixLength; i++){
				            package_ = sitaShops.Package[i];
				            if (package_.id == entityId){
					           entityName = package_.title;
					           type = type_package;
					           break;
				        }
			     }
		  }
		  _gaq.push(['_trackEvent', 'webshop', type, entityName]);
	   } catch (e) {}
}

function trackSubSelection(self, stream){	
	   lineTitle = "";
	   if ($(self).parent().attr("directuper") > 0) {
		      lineTitle = $(self).parent().parent().find("h2").html(); // for DIRECT type lower line 
	   } else {
		      lineTitle = $(self).parent().find("h2").html();
	   }
		_gaq.push(['_trackEvent', lineTitle, $(self).attr("entitytitle"), stream.title]);
}


function setSelectToItem(priceItemId){
	   var price = 0;
	   try{		
		      var parent = $('*[lineContent]');
		      var idLine = parent.attr('lineContent');
			     for(var i = 0; i < sitaShops.WasteStream.length-fixLength; i++){
			         var stream = sitaShops.WasteStream[i];
			         if(stream.id==idLine){
				            stream.priceItemId = priceItemId;
				            for(var j = 0; j < stream.prices.length-fixLength; j++){
					           //Only for Direct
						          if(lowerIdNew!=null && $(stream).attr('type')=='DIRECT') $(stream).attr('lowerEntity',lowerIdNew);
					           //
					               if($(stream.prices[j]).attr('id')==priceItemId){
						                  price = stream.prices[j].price;
						                  stream.price = price;
						                  upperId = stream.prices[j].upperEntityId;
						                  lowerId = stream.prices[j].lowerEntityId;
						                  break;
					               }
				            }					
				            break;
			         }
		      }
	   }catch (e){}
    $('.ssItem',parent).removeClass('itemSelected');
    $('*[upperId='+upperId+']',parent).addClass('itemSelected');
    $('*[lowerId='+lowerId+']',parent).addClass('itemSelected');

    if(stream.priceItemId!=null){
        $('.orderBtn .submit',parent).attr('priceItemId',stream.priceItemId);		
    }
}
    
function setTitleContentPage(idRte,title){
	   var dialog = $('<DIV id="transl_dialog" title="Edit title of content"><img class="loader" src="/images/loadingAnimation.gif" /></DIV>');
	   var curTitle = $('#titleContent').text();
	   $(dialog).dialog({
		      width: 330,
		      height: 120,
		      modal: true,
		      open: function(){
			         var dialog = this;			
			         dialog.innerHTML ='<textarea name="newTitle" id="newTitle" class="admTextArea" '+
					                           'style="width: 300px;height:20px;" rows="1">'+curTitle+'</textarea>';
		          },
		      buttons: {
			     '< Save and close >': function(){
				        var newTitle = $('#newTitle',dialog).val();
				        AJAX_Send("update-article-info-command", {id : idRte, head : "main "+newTitle});
				        $('#titleContent').html(newTitle);
				        $(this).dialog('close');
			     },
			     '< Cancel >': function() {
			         $(this).dialog('close');}
		      },
		      close: function() {
			         $(this).remove();
		      }
	   });
}

/* Popup Banner*/
$(document).ready(function(){	
    var dialogGratis = $('<DIV id="dialog_pointGratis" title=""></DIV>');
	   $(dialogGratis).append($('.gratisRTEText'));	
	   $('*.pointGratis').click(function(e){	 
		      popupBannerOnLoad(dialogGratis,'gratisRTEText');
		      return false;
	   });
	   
	   createDialogContract();    
})

function createDialogContract(){            
    $('#dialog_contractduurRTEText').remove();
    var dialogContractduur = $('<DIV id="dialog_contractduurRTEText" title=""></DIV>');	   
	   $(dialogContractduur).append($('.contractduurRTEText'));	   
	   $('*.period > a').click(function(e){		      		      
		      popupBannerOnLoad(dialogContractduur,'contractduurRTEText');
		      return false;
	   })
}

function popupBannerOnLoad(dialogRTE,block){
    $(dialogRTE)
        .dialog({		          
		          bgiframe: true,
		          width: 740,
		          position: ['center','top'],
		          modal: true,
		          dialogClass: 'popupBlock',
		      open: function(){			         
			         var dialog = this;			         
			         $('.'+block, dialog).css('display','block');			         
		      },
		      close: function() {			         
			         $(this).remove();
		      }
	   });
}
