var spinnerImg = new Element('img', {
    'src': 'images/ajax-loader.gif'
});
var spinnerCode = "images/ajax-loader.gif";
var ie = false;

var HashUri = new Class({
  path : "",
  category : "",
  subcategory : "",
  product : "",
  tab : "",
  
  setCategory : function(c) {
    this.category = c.replace(/#/g,'');
    this.setSubcategory("");
  },
  setSubcategory : function(c) {
    this.subcategory = c;
    this.setProduct("");
  },
  setProduct : function(c) {
    this.product = c;
    this.setTab("");
  },
  setTab : function(c) {
    this.tab = c;
  },
  getCategory : function() {
    return this.category;
  },
  getSubcategory : function() {
    return this.subcategory;
  },
  getProduct : function() {
    return this.product;
  },
  getTab : function() {
    return this.tab;
  },
  set : function(c) {
    this.path = c.replace(/%20/g,' ');
  },
  get : function() {
    return this.path;
  },
  polacz : function() {
    if(this.category != "") {
      this.path = "#"+this.category;
      if(this.subcategory != "") {
        this.path = this.path+"/"+this.subcategory;
      }
      if(this.product != "") {
        this.path = this.path+"/"+this.product;
        if(this.tab != "") {
          this.path = this.path+"/"+this.tab;
        }
      }
    }
  },
  rozdziel : function() {
    if(this.path.test("#.+/.+/.+/.+", 'i')) {  ///   #(category)/(subcategory)/(product)/(tab)
      var match = /#(.+)\/(.+)\/(.+)\/(.+)/i.exec(this.path);

      this.category = match[1];
      this.subcategory = match[2];
      this.product = match[3];
      this.tab = match[4];
    } else
    if(this.path.test("#.+/.+/.+", 'i')) {  ///   #(category)/(subcategory)/(product) lub #(category)/(product)/(tab)
      var match = /#(.+)\/(.+)\/(.+)/i.exec(this.path);

      this.category = match[1];
      this.subcategory = match[2];
      this.product = match[3];
      this.tab = "";
    } else 
    if(this.path.test("#.+/.+", 'i')) {  ///   #(category)/(subcategory) lub #(category)/(product)
      var match = /#(.+)\/(.+)/i.exec(this.path);

      this.category = match[1];
      this.subcategory = match[2];
      this.product = "";
      this.tab = "";
    } else 
    if(this.path.test("#.+", 'i')) {  ///   #(category)
      var match = /#(.+)/i.exec(this.path);

      this.category = match[1];
      this.subcategory = "";
      this.product = "";
      this.tab = "";
    } else {

      this.category = "";
      this.subcategory = "";
      this.product = "";
      this.tab = "";
    }
  },
  setToAddressBar : function() {
    window.location.hash = this.get();
  },
  loadFromAddressBar : function() {
    this.set(window.location.hash);
  },
  clear : function() {
    this.set("");
    this.rozdziel();
  }
  
});

var _pp = new HashUri();
_pp.loadFromAddressBar();
_pp.rozdziel();   

PreloadImages();

window.addEvent('domready', function(){
	// IE6 fix
	if ((Browser.Engine.trident) && (Browser.Engine.version<5)) {
		new Asset.css('css/ie6.css');
		ie = true;
	}
/////////////////////////////////////////

	// global rollovers 
	applyRollovers($$(".rollover"));
	
	// product selector 
	if ($('popup_container')) {
		enableProducts();
	}	
	
	// acc finder
	if ($('finderbrand')) {
		enableFinder();
	}		
	
	if ($('supportbrand')) {
		enableSupport();
	}		
	
	if($('slrproduct')) {
		enableSlr();		
	}

	if($('downloadform')) {
		enableDownload();
	}
	
	if($('news_popup_container')) {
	  enableNews();
  }


	if($('admin_container')) {
	  enableAdmin();
  }

	// enable search events
	enableSearch();

});  
// end domready ==============================



// =============================FUNCTIONS ==============================
// enable news
function enableNews() {
  $('news_popup_container').hide();

  if($('list_content'))
		makeScrollbar($('list_content'), $('list_scrollbar'), $('list_scrollhandle'));

  if($('celebrities_list_content'))
		makeScrollbar($('celebrities_list_content'), $('celebrities_list_scrollbar'), $('celebrities_list_scrollhandle'));
		
  if($('press_list_content'))
		makeScrollbar($('press_list_content'), $('press_list_scrollbar'), $('press_list_scrollhandle'));

//  if($('search_result_content'))
//		makeScrollbar($('search_result_content'), $('search_result_scrollbar'), $('search_result_scrollhandle'));

}
// enable product selector page
function enableProducts() {
	var popupPanel = $('popup_container');
	
	var productButtons = $$(".slider_b");
	productButtons.each(function(productButton, i) {
		// extract the ID
		var butId = productButton.get('id');
		butId = butId.substr(8, 1);
		productButton.butId = butId;
		
		// MANAGE THE EXTRA BUTTONS
		var extraButton = $("slider_x" + butId);
		var slideArea = $('slider_' + butId);		
		//extraButton.set('href','#');
		extraButton.addEvent("click", function() {
			productButton.fireEvent("click");
			slideArea.setStyle('margin-left', '0px');
			/*window.location.hash = butId + "/"; */
		});
		// custom rollovers
		extraButton.addEvent("mouseenter", function() {
			slideArea.set('tween', {duration: 150, link: 'cancel'});
			slideArea.tween('margin-left', '20px');
		});		
		extraButton.addEvent("mouseleave", function() {
			slideArea.set('tween', {duration: 150, link: 'cancel'});
			slideArea.tween('margin-left', '0px');
		});				
		
		// remove hyperlink
		//productButton.set('href','#');		
		// CLICK EVENT
		productButton.addEvent("click", function() {
		    _pp.setCategory(productButton.get("href"));
        _pp.polacz();
        _pp.setToAddressBar();
			// reveal product details layer (in case it's the 1st time)
			popupPanel.setStyle('display','block');					
			// remove extra buttons (in case it's the 1st time)
			var extraButtons = $$(".slider_bt_extra");
			extraButtons.each(function(extraButton, i) {
				extraButton.destroy();
			});
			
			// remove any product details
			popupPanel.empty();
			
			// init variables
			var minX = -19;
			var currentX = 0;
			var targetX = 0;
			var widthX = 24;
			var widthOpen = 852;
			var currentPanel = null;
			var myTransition = new Fx.Transition(Fx.Transitions.Sine, 3);				
			
			// move all the sections
			for(i=1; i<7; i++) {
				// slide left or right
				if (i<=this.butId) {  targetX = minX + (widthX * i); }
				if (i>this.butId) {  targetX = minX + (widthX * i) + widthOpen; }
				currentPanel = $$('#slider_' + i);				

				// change width of the photograph container
				if(i==this.butId) {  // current button
					// photo grow
					var openPanel = currentPanel.getElement('.slider_bg');			
					var openImage = openPanel.getElement('img');
					openImage.set('tween', {duration: 500});					
					openImage.tween('left', '0px');
					// move popup window to correct position
					var newX = (widthX * this.butId);
					// correction of positioning 
					//if (this.butId == 1) { newX = 0; } else { newX = newX + 5; }
					popupPanel.setStyle('left', newX);
					popupPanel.set('category', this.butId);
					// load and fade in popup window slowly
					loadCategoryList.delay(250); 
				} 
				// move the panels
				this.setStyle('margin-left', '0px');
				currentPanel.set('tween', {duration: 'normal', transition: myTransition.easeOut});
				currentPanel.tween('left', targetX);			
			}
		});

	});
	// fire off event if required
	if(selcategory>0) {
		var clickedButton = $('slider_b' + selcategory);
		clickedButton.fireEvent('click');
	}
}

// enable finder forms
function enableFinder() {
	$('finderbrand').addEvent("change", function() {
		// load and show the list of models
		var selected = $('finderbrand').getSelected();
		var model = selected.getProperty('value');
		
		var urlPath = "lib/getcontent.php?type=findermodels&cat=" + model;
		
		var req = new Request.HTML({
			url:urlPath, 
			method:'get',		
			onSuccess: function(html) {	
				// display categories
				var wrapper = $('findermodelwrapper');	
				wrapper.empty();
				wrapper.adopt(html);
				$('model').addEvent("change", function() {
					$('searchwrapper').setStyle('display','block');	
				});
			}
		});
		req.send();		
	});
}

function finderFinal(category, model, catname) {
	var urlPath = "lib/getcontent.php?type=finderfinal&cat=" + category + "&prodid=" + model + "&page=" + catname;
	var req = new Request.HTML({
			url:urlPath, 
			method:'get',		
			onSuccess: function(html) {	
				// display categories
				var wrapper = $('finalfinder');	
				wrapper.empty();
				wrapper.adopt(html);
			}
		});
	req.send();
}

// enable support forms
function enableSupport() {
	$('supportbrand').addEvent("change", function() {
		// load and show the list of models
		var selected = $('supportbrand').getSelected();
		var model = selected.getProperty('value');
		
		var urlPath = "lib/getcontent.php?type=supportmodels&cat=" + model + "&catname=" + selected.getProperty('text');
		
		var req = new Request.HTML({
			url:urlPath, 
			method:'get',		
			onSuccess: function(html) {	
				// display categories
				var wrapper = $('supportmodelwrapper');	
				wrapper.empty();
				wrapper.adopt(html);
				$('supportmodel').addEvent("change", function() {
					var selectedmodel = $('supportmodel').getSelected();
					var modelurl = selectedmodel.getProperty('value');
					if(modelurl != '-1') {
  					window.location = modelurl;
  					
          } else {
        		var urlPath = "lib/getcontent.php?type=notlistedmodel";
                                      
        		var req = new Request.HTML({
        			url:urlPath, 
        			method:'get',		
        			onSuccess: function(html) {
            				var wrapper = $('details');	
            				wrapper.empty();
            				wrapper.adopt(html);
            				wrapper.setStyle('height', '421px');
            				wrapper.setStyle('padding', '0px');
                    /////////////////////////////////////////////////////////////////
	$('f_country').addEvent("change", function() {
	  if($('f_country').value != "0" && $('f_type').value != "0") {
      $('would_call').set('text', 'I would like to call.');
    }
	});
	$('f_type').addEvent("change", function() {
	  if($('f_country').value != "0" && $('f_type').value != "0") {
      $('would_call').set('text', 'I would like to call.');
    }
		// load and show the list of models
		var selected = $('f_type').getSelected();
		var type = selected.getProperty('value');

    $('cf_company_name').setStyle('display', 'none');
    $('cf_email').setStyle('display', 'none');
    $('cf_telephone').setStyle('display', 'none');
    $('cf_address').setStyle('display', 'none');
    $('cf_enquiry').setStyle('display', 'none');
    $('cf_submit').setStyle('display', 'none');
    $('cf_name').setStyle('display', 'none');
    $('cf_rate').setStyle('display', 'none');


    if(type == 1 || type == 3 || type == 4 || type == 5 || type == 6 || type == 7 ) {
      $('cf_email').setStyle('display', '');
      $('cf_telephone').setStyle('display', '');
      $('cf_address').setStyle('display', '');
      $('cf_enquiry').setStyle('display', '');
      $('cf_submit').setStyle('display', '');
      
      if(type == 1 || type == 7) {
      // customer + rating
        $('cf_name').setStyle('display', '');
        $('cf_rate').setStyle('display', '');
      } else
      if(type == 3) {
      // customer
        $('cf_name').setStyle('display', '');
      } else
      if(type == 4 || type == 5 || type == 6) {
      // corporate
        $('cf_company_name').setStyle('display', '');
      }

    } else
    if(type == 2) {
    // switch to support tab if exist
    /*
      var content = tabPane.container.getElements(tabPane.options.contentSelector);
      content.each(function(e, i){
        if(e.get('id') == 'tab_support') {
          tabPane.showTab(i);
          $('f_type').set('value', 0);
        }
      });    */
    }
    
		$('f_submit').addEvent("click", function() {
		
  		var urlPath = "lib/getcontent.php?type=contactus&product="+$('f_product').value+
                    "&enquiry_type="+$('f_type').value+
                    "&country="+$('f_country').value+
                    "&name="+$('f_name').value+
                    "&company_name="+$('f_company_name').value+
                    "&email="+$('f_email').value+
                    "&telephone="+$('f_telephone').value+
                    "&address="+$('f_address').value+
                    "&rate="+$('f_rate').value+
                    "&enquiry="+$('f_enquiry').value;
  		
  		var req = new Request.HTML({
  			url:urlPath, 
  			method:'get',		
  			onSuccess: function(html) {	
  				// display categories
  				var wrapper = $('popup_form_contact');	
  				wrapper.empty();
  				wrapper.adopt(html);
  			}
  		});
  		req.send();
    });
   });            				
          
    $('would_call').addEvent("click", function() {
  		var urlPath = "lib/getcontent.php?type=wouldcall&country="+$('f_country').value+"&enquiry_type="+$('f_type').value;

  		var req = new Request.HTML({
  			url:urlPath, 
  			method:'get',		
  			onSuccess: function(html) {	
  				// display categories
  				var wrapper = $('would_call');	
  				wrapper.empty();
  				wrapper.adopt(html);
  			}
  		});
  		req.send();
    });      				
            				
            				//////////////////////////////////////////////////////////////////
            	}
            });
            req.send();	
            
          }
				});
			}
		});
		req.send();		
	});
	

	// process feedback form
	/*
	$('feedbacknotice').fade('hide');
	
	$('submitfeedback').addEvent("click", function() {	
		// validation first
		$('feedbacknotice').fade('hide');
		var allFields = $$('.formfield');
		var data = "";
		var email = "";
		
		allFields.each(function(thisField,i) {
				if ((thisField.value).length<3) {
					thisField.addClass('highlight');
					$('feedbacknotice').fade('show');
				} else {
					thisField.removeClass('highlight');
				}
				var name = thisField.name;
				data += thisField.name + " = " + thisField.value + "<br>";
				if(thisField.name==email) { email=thisField.value; }
		})

		if ($('feedbacknotice').getStyle('opacity')==0) {
				// send email if ok
				var urlPath = "lib/getcontent.php?type=feedback&data=" +data+"&recipient=" + email;
				
				var req = new Request.HTML({
					url:urlPath, 
					method:'get',		
					onSuccess: function(html) {	
						// display categories
						var wrapper = $('feedbackform');	
						wrapper.empty();
						wrapper.adopt(html);
					}
				});
				req.send();
		}
    });
	*/
}

// enable download form
function enableDownload() {
	// process feedback form
	$('downloadnotice').fade('hide');
	
	$('submitdownload').addEvent("click", function() {	

		// validation first
		$('downloadnotice').fade('hide');

		if (($('name').value).length<3) {
				$('name').addClass('highlight');
				$('downloadnotice').fade('show');
		} else {
				$('name').removeClass('highlight');
				var vname = $('name').value;
		}		

		if ((($('email').value).length<7) || ($('email').value.indexOf(".") < 2) || ($('email').value.indexOf("@") == 0)) {
				$('email').addClass('highlight');
				$('downloadnotice').fade('show');
		} else {
				$('email').removeClass('highlight');
				var vemail = $('email').value;	
		}		
		
		if ((($('mid').value).length<7) && (!isNaN($('mid').value))) {
				$('mid').addClass('highlight');
				$('downloadnotice').fade('show');
		} else {
				$('mid').removeClass('highlight');
				var vmid = $('mid').value;	
		}
		
		// send if valid
		if ($('downloadnotice').getStyle('opacity')==0) {
				// send email if ok
				var urlPath = "lib/getcontent.php?type=download&vname=" +vname+"&vemail=" + vemail + "&vmid=" + vmid + "&vretailer=" + $('retailer').value + "&vproduct=" + $('product').value + "&vsubscribe=" + $('subscribe').checked + "&vcomments=" + $('comments').value;
				
				var req = new Request.HTML({
					url:urlPath, 
					method:'get',		
					onSuccess: function(html) {	
						// display categories
						var wrapper = $('downloadform');	
						wrapper.empty();
						wrapper.adopt(html);
					}
				});
				req.send();
		}
    });
}


// load and show content (Ajax)
function loadCategoryList() {
	var popupPanel = $('popup_container');
	var category = popupPanel.get('category');	
	popupPanel.empty();
	//popupPanel.grab(spinnerImg);
	
	var urlPath = "lib/getcontent.php?type=catlist&cat=" + category + "&prev="+prev_mode;

	// load category list
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',		
		onSuccess: function(html) {	
			// display categories
			var catList = new Element('div', {
			    'id': 'popup_catlist'
			});
			catList.adopt(html);
			// skip category listing if single category
			if(catList.get('html').indexOf("no_category")>-1) {
				// add punch line panel
				var punchPanel = new Element('div', {'id': 'popup_punch'});
				popupPanel.grab(punchPanel);
				// punchline
				var so = new SWFObject( "images/flash/" + category + ".swf", "Product image", "340", "430", "8");
				so.addParam("wmode", "transparent");
				so.write("popup_punch");
				// and skip to categories
				loadProductList(category);
			} else {
				popupPanel.empty();
				popupPanel.fade('hide');
				popupPanel.grab(catList);
				popupPanel.fade('in');
				// enable link highlight
				var allLinks = $$('#popup_catlist a');
				allLinks.each(function(thisLink, i) {
					thisLink.addEvent('click', function() {
						var allLinks = $$('#popup_catlist a');
							allLinks.each(function(thisLink, i) {
							thisLink.removeClass('selected');
					       });
						this.addClass('selected');							
					});
				});
				// enforce action if subcategory set
				if(selsubcategory>0) {
					loadProductList(selsubcategory);
				}
				// add punch line panel
				var punchPanel = new Element('div', {'id': 'popup_punch'});
				popupPanel.grab(punchPanel);
				var so = new SWFObject( "images/flash/" + category + ".swf", "Product image", "340", "430", "8");
				so.addParam("wmode", "transparent");
				so.write("popup_punch");
			}
		}
	});
	req.send();
	
}

function loadProductList(category) {
  _pp.setSubcategory(category);
  _pp.polacz();
  _pp.setToAddressBar();

	var popupPanel = $('popup_container');

	// remove previous list if exists
	if ($('popup_prodlist')) {
		$('popup_prodlist').destroy();
	}
	if ($('popup_details')) {
		$('popup_details').destroy();
	}	

	// we can create the product list now as it's not optional
	var prodList = new Element('div', {
	    'id': 'popup_prodlist'
	});
	prodList.fade('hide');
	prodList.grab(spinnerImg);	
	popupPanel.grab(prodList);
	prodList.fade('in');

	var urlPath = "lib/getcontent.php?type=prodlist&cat=" + category + "&prev="+prev_mode;

	// load category list
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',		
		onSuccess: function(html) {
			// display categories
			prodList.empty();
			prodList.adopt(html);
			// enable link highlight
			var allLinks = $$('#popup_prodlist a');
			allLinks.each(function(thisLink, i) {
				thisLink.addEvent('click', function() {
					var allLinks = $$('#popup_prodlist a');
						allLinks.each(function(thisLink, i) {
						thisLink.removeClass('selected');
				       });
					this.addClass('selected');						
				} );
			});		
			// enforce action if product set
			if(selproduct>0) {
				// clear variables after the call
				selcategory = 0;
				selsubcategory =0;
				var stemp = selproduct;
				selproduct = 0;
				showProductDetails(stemp);
			}

      new JustTheTip('.needs-tip', {
        /*tip_html : 'You will never see this.',  */
        show_delay : 0,
        hide_delay : 200,
        fade_in_duration : 250,
        fade_out_duration : 500,
        position: {position: 'topRight', offset: {x: 11, y: -10}},
        
        onTipShown: function(tip,elem,jtt){
          var dd = document.getElementById('div_' + elem.get('id'));
          tip.set('html', "<div>" + dd.get('html') + "</div>");
        }        
      });	

		}
	});
	req.send();
	

	// ************** mark/unmark the selected link		
	
}

function showProductDetails(productid) {
  _pp.setProduct(productid);
  _pp.polacz();
  _pp.setToAddressBar();

	var popupPanel = $('popup_container');
	// remove previous list if exists
	if ($('popup_details')) {
		$('popup_details').destroy();
	}
	// add product details
	var prodDetails = new Element('div', {
	    'id': 'popup_details'
	});
	if ($('popup_punch')) {
		$('popup_punch').destroy();
	}
	
	prodDetails.fade('hide');
	prodDetails.grab(spinnerImg);	
	popupPanel.grab(prodDetails);
	prodDetails.fade('in');		

	var urlPath = "lib/getcontent.php?type=proddetails&page=all&prodid=" + productid + "&ie=" + ie;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			prodDetails.empty();
			prodDetails.adopt(html);
			applyRollovers($$("#popup_nav .rollover"));
			
			// handle the scrollbars
      if($('popup_content1'))
        makeScrollbar($('popup_content1'), $('popup_scrollbar1'), $('popup_scrollhandle1'));
      if($('popup_content'))
  			makeScrollbar($('popup_content'), $('popup_scrollbar'), $('popup_scrollhandle'));
      if($('popup_content3'))
  			makeScrollbar($('popup_content3'), $('popup_scrollbar3'), $('popup_scrollhandle3'));
      if($('popup_content4'))
  			makeScrollbar($('popup_content4'), $('popup_scrollbar4'), $('popup_scrollhandle4'));

 			makeScrollbar($('popup_form_contact'), $('popup_scrollbarform'), $('popup_scrollhandleform'));
			// enable photo popup
			enableLargePhoto();
			// go to downloads page if required
/*			if(selpage!="none") {
				switchProductDetails(selproduct, selpage);
				selproduct=0;
				selcategory=0;
				selsubcategory=0;
			}*/
			
      //tabs			
      var tabPane = new TabPane("popup_tabs", {
        tabSelector: "a.tab_sel",
        contentSelector: "div.tab_tab"
      });


      function mycarousel_initCallback(carousel) {
          JQ('.carousel_thumb').bind('click', function() {
              carousel.scroll(JQ.jcarousel.intval(JQ(this).attr("id").substring(6,7)));
              carousel.options.auto = 0;
              carousel.stopAuto();
              
              JQ('.carousel_thumb').removeClass('active');
              JQ(this).addClass('active');
              return false;
          });
          JQ('#popup_tabs').bind('wylacz', function() {
              carousel.stopAuto();
              return false;
          });
          JQ('#popup_tabs').bind('wlacz', function() {
              carousel.startAuto(5);
              return false;
          });
      };

      function mycarousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
        JQ('.carousel_thumb').removeClass('active');
        JQ(".carousel_thumb" ).each(
        function( intIndex ){
          if(intIndex == (idx - 1)) {
            JQ(this).addClass('active');
          }
        });
      };

      if(JQ(".carousel_thumb" ).length < 6) {
        JQ('#thumb_carousel').jcarousel({
          scroll: 5,
          buttonNextHTML: null,
          buttonPrevHTML: null
        });
      } else {
        JQ('#thumb_carousel').jcarousel({
          scroll: 5
        });
      } 
      JQ('#photo_carousel').jcarousel({
        auto: 5,
        scroll: 1,
        wrap: 'last',
        initCallback: mycarousel_initCallback,
        itemVisibleInCallback: {
                    onAfterAnimation: mycarousel_itemVisibleInCallbackAfterAnimation
                }
      });


      tabPane.addEvents({
      		change: function(ind) {
          if(ind == 0) {
            JQ('#popup_tabs').trigger('wlacz');
          } else {
            JQ('#popup_tabs').trigger('wylacz');
          }
        }
      });

  
    	$('f_country').addEvent("change", function() {
    	  if($('f_country').value != "0" && $('f_type').value != "0") {
          $('would_call').set('text', 'I would like to call.');
        }
    	});
    	$('f_type').addEvent("change", function() {
    	  if($('f_country').value != "0" && $('f_type').value != "0") {
          $('would_call').set('text', 'I would like to call.');
        }
    
    		// load and show the list of models
    		var selected = $('f_type').getSelected();
    		var type = selected.getProperty('value');
    
        $('cf_company_name').setStyle('display', 'none');
        $('cf_email').setStyle('display', 'none');
        $('cf_telephone').setStyle('display', 'none');
        $('cf_address').setStyle('display', 'none');
        $('cf_enquiry').setStyle('display', 'none');
        $('cf_submit').setStyle('display', 'none');
        $('cf_name').setStyle('display', 'none');
        $('cf_rate').setStyle('display', 'none');
    
    
        if(type == 1 || type == 3 || type == 4 || type == 5 || type == 6 || type == 7 ) {
          $('cf_email').setStyle('display', '');
          $('cf_telephone').setStyle('display', '');
          $('cf_address').setStyle('display', '');
          $('cf_enquiry').setStyle('display', '');
          $('cf_submit').setStyle('display', '');
          
          if(type == 1 || type == 7) {
          // customer + rating
            $('cf_name').setStyle('display', '');
            $('cf_rate').setStyle('display', '');
          } else
          if(type == 3) {
          // customer
            $('cf_name').setStyle('display', '');
          } else
          if(type == 4 || type == 5 || type == 6) {
          // corporate
            $('cf_company_name').setStyle('display', '');
          }
    
        } else
        if(type == 2) {
        // switch to support tab if exist
          var content = tabPane.container.getElements(tabPane.options.contentSelector);
          content.each(function(e, i){
            if(e.get('id') == 'tab_support') {
              tabPane.showTab(i);
              $('f_type').set('value', 0);
            }
          });    
        }
        
    
    		$('f_submit').addEvent("click", function() {
    		
      		var urlPath = "lib/getcontent.php?type=contactus&product="+$('f_product').value+
                        "&enquiry_type="+$('f_type').value+
                        "&country="+$('f_country').value+
                        "&name="+$('f_name').value+
                        "&company_name="+$('f_company_name').value+
                        "&email="+$('f_email').value+
                        "&telephone="+$('f_telephone').value+
                        "&address="+$('f_address').value+
                        "&rate="+$('f_rate').value+
                        "&enquiry="+$('f_enquiry').value;
      		
      		var req = new Request.HTML({
      			url:urlPath, 
      			method:'get',		
      			onSuccess: function(html) {	
      				// display categories
      				var wrapper = $('popup_form_contact');	
      				wrapper.empty();
      				wrapper.adopt(html);
      			}
      		});
      		req.send();
        });
        
        $('would_call').addEvent("click", function() {
      		var urlPath = "lib/getcontent.php?type=wouldcall&country="+$('f_country').value+"&enquiry_type="+$('f_type').value;
    
      		var req = new Request.HTML({
      			url:urlPath, 
      			method:'get',		
      			onSuccess: function(html) {	
      				// display categories
      				var wrapper = $('would_call');	
      				wrapper.empty();
      				wrapper.adopt(html);
      			}
      		});
      		req.send();
        });    
        		
    	});


      if($('wielkiTest')) {
      	$('wielkiTest').addEvent("click", function() {
          tabPane.showTab(tabPane.getCount() - 1);
      
       		$('downloadnotice').fade('hide');
        	$('submitdownload').addEvent("click", function() {
         		$('downloadnotice').fade('hide');
      
        		// validation first
        
        		if (($('name').value).length<3) {
        				$('name').addClass('highlight');
        				$('downloadnotice').fade('show');
        		} else {
        				$('name').removeClass('highlight');
        				var vname = $('name').value;
        		}		
        
        		if (($('email').value).match(/^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i)) {
        				$('email').removeClass('highlight');
        				var vemail = $('email').value;	
        		} else {
        				$('email').addClass('highlight');
        				$('downloadnotice').fade('show');
        		}		
        		
        		if ((($('mid').value).length<7) || (!($('mid').value).match(/^[-+]?[0-9]+$/))) {
        				$('mid').addClass('highlight');
        				$('downloadnotice').fade('show');
        		} else {
        				$('mid').removeClass('highlight');
        				var vmid = $('mid').value;	
        		}
        		
        		// send if valid
        		if ($('downloadnotice').getStyle('opacity')==0) {
        				// send email if ok
        				var urlPath = "lib/getcontent.php?type=download&vname=" +vname+"&vemail=" + vemail + "&vmid=" + vmid + "&vretailer=" + $('retailer').value + "&vproduct=" + $('product').value + "&vsubscribe=" + $('subscribe').checked + "&vcomments=" + $('comments').value;
      
      					var wrapper = $('popup_form_download');	
      
        				var req = new Request.HTML({
        					url:urlPath, 
        					method:'get',		
        					onSuccess: function(html) {	
      
        						wrapper.empty();
        						wrapper.adopt(html);
        					}
        				});
        				req.send();
        		}
            });	
      
          });
        }
        enableLargePhotos();
        
        if(selpage != "none") {
          if(selpage == 'Overview') {
            var tab_id = 'tab_overview';
          } else
          if(selpage == 'Technical Specifications') {
            var tab_id = 'tab_techspec';
          } else
          if(selpage == 'Support') {
            var tab_id = 'tab_support';
          } else
          if(selpage == 'Where To Buy') {
            var tab_id = 'tab_where_to_buy';
          } else
          if(selpage == 'Contact') {
            var tab_id = 'tab_contact_form';
          } else
          if(selpage == 'Software Download') {
            var tab_id = 'tab_software_download';
          }
          var content = tabPane.container.getElements(tabPane.options.contentSelector);
          content.each(function(e, i){
            if(e.get('id') == tab_id) {
              tabPane.showTab(i);
              _pp.setTab(selpage);
              _pp.polacz();
              _pp.setToAddressBar();
              selpage="none";
            }
          });    
        }
        
    		$('enlarg_close_button').set("href", "#");
        repairHashUrl();
////			
		}
	});
	req.send();  
}

function switchProductDetails(productid, page) {
	var prodColumn = $('.popup_column2');	
	// mark prod as selected
	var urlPath = "lib/getcontent.php?type=proddetails&page=" + page + "&prodid=" + productid + "&ie=" + ie;
	prodColumn.empty();
	prodColumn.adopt(spinnerImg);	

	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			prodColumn.empty();			
			prodColumn.adopt(html);
			// handle the scrollbars
			makeScrollbar($('popup_content'), $('popup_scrollbar'), $('popup_scrollhandle'));
		}
	});
	req.send();  
}

// preload assets
function PreloadImages() {
	// list images to be preloaded
	new Asset.image('images/body_bg.png');
	new Asset.image('images/container_bg.png');	
	new Asset.image('images/home_gradient_bg.png');
	new Asset.image('images/footer_bg.png');	
	// preload bars
	new Asset.image('images/prodsel_b1.png');
	new Asset.image('images/prodsel_b2.png');
	new Asset.image('images/prodsel_b3.png');
	new Asset.image('images/prodsel_b4.png');
	new Asset.image('images/prodsel_b5.png');
	new Asset.image('images/prodsel_b6.png');	
	new Asset.image('images/prodsel_b1_over.png');
	new Asset.image('images/prodsel_b2_over.png');
	new Asset.image('images/prodsel_b3_over.png');
	new Asset.image('images/prodsel_b4_over.png');
	new Asset.image('images/prodsel_b5_over.png');
	new Asset.image('images/prodsel_b6_over.png');		
	// preload product images
	new Asset.image('images/prodsel_photo1.jpg');
	new Asset.image('images/prodsel_photo2.jpg');
	new Asset.image('images/prodsel_photo3.jpg');
	new Asset.image('images/prodsel_photo4.jpg');
	new Asset.image('images/prodsel_photo5.jpg');
	new Asset.image('images/prodsel_photo6.jpg');	
}

function makeScrollbar(content,scrollbar,handle){
//if($$(content)) {
//alert($$(content));
	if (content) {
		var contentSize = content.getSize().y;
		var scrollSize= content.getScrollSize().y;	
		var steps = scrollSize - contentSize;
	} else {
		steps = 0;
	}

	if (steps > 0) {
	  scrollbar.fade('show');
		var slider = new Slider(scrollbar, handle, {	
			steps: steps,
			mode: 'vertical',
			onChange: function(step){
				// Scrolls the content element in x or y direction.
				content.scrollTo(0, step);
			}
		}).set(0);
	
		// Scroll the content element when the mousewheel is used within the 
		// content or the scrollbar element.
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
			e = new Event(e).stop();
			var step = slider.step - e.wheel * 30;	
			slider.set(step);					
		});
	
		// Stops the handle dragging process when the mouse leaves the document body.
		$(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
	} else {
		if(scrollbar) {
      scrollbar.fade('hide');
    }
	}
//}

}	
	
function applyRollovers(rolloverButtons) {
	//if (ie==false) {
		rolloverButtons.each(function(rolloverButton, i) {
			//get path and preload images
			var butPath = rolloverButton.get('src');	
			var butLen = butPath.length;
			var butExt = butPath.substr(butLen - 4, 4);
			butPath = butPath.substr(0, butLen - 4);
			var newPath = butPath + "_over" + butExt;	
			var preload = new Asset.image(newPath);				
		
			//rollovers activate
			rolloverButton.addEvent("mouseenter", function() {
				F_addOver(this);
			});
			rolloverButton.addEvent("mouseleave", function() {						       
				F_removeOver(this);
			});	
		});
	//}
}
// functions for rollovers
function F_addOver(element) {
	var butPath = element.get('src');
	var butLen = butPath.length;
	var butExt = butPath.substr(butLen - 4, 4);
	butPath = butPath.substr(0, butLen - 4);
	var newPath = butPath + "_over" + butExt;	
	element.set('src', newPath);
}
function F_removeOver(element) {
	var butPath = element.get('src');
	var newPath = butPath.replace("_over.", ".");
	element.set('src', newPath);
}

// jump menu activator used for the country selector
function F_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
}
function enableSearch() {
	$('searchgo').addEvent("click", function() {
		$('searchform').submit();
	});
	$('searchfield').addEvent("click", function() {
		$('searchfield').set("value","");
	});
  
  if($('searchresults'))
		makeScrollbar($('searchresults_content'), $('searchresults_scrollbar'), $('searchresults_scrollhandle'));

  	
}
function subscriptionHandle() {
				var email = $("subscription_email").get("value");
				if ((email.indexOf("@")>-1) && (email.length>10)) {
					// send subscription
					var req = new Request.HTML({
						url:"lib/subscribe.php?email=" + email, 
						method:'get',
						onSuccess: function(html) {
							$('subscription_message').set("text", "Thank you, you will be notified soon!");	
							$("subscription_email").set("");
						}
					});
					req.send();  
				} else {
					$('subscription_message').set("text", "Please enter a valid email address.");
				}
}

function loadPhoto(path) {
	var popupPhoto = $('.popup_photo').getElement('img');
	popupPhoto.set('src', path);
	// preload the large photo so it opens quicker
	imgSource = path.replace(".jpg", "_large.jpg");
	var myImage = new Asset.image(imgSource);
	
	// makes the popup
	$('.popup_photo').removeEvents("click");	
	enableLargePhoto();
}

function enableLargePhoto() {
	$$('.popup_photo').addEvent("click", function() {
				// identify the img source
				var popupPhoto = $('.popup_photo').getElement('img');
				var imgSource = popupPhoto.get("src");
				imgSource = imgSource.replace(".jpg", "_large.jpg");
				// display or resize the image
				var myImage = new Asset.image(imgSource, {onload: EnlargementOpen});
	});
}
function enableLargePhotos() {
  $$('.popup_large').each(function(popupPhoto){

  	popupPhoto.addEvent("click", function() {
  				// identify the img source
  				var imgSource = popupPhoto.get("src");
  				imgSource = imgSource.replace(".jpg", "_large.jpg");
  				// display or resize the image
  				var myImage = new Asset.image(imgSource, {onload: function(){
  				  EnlargementOpen(popupPhoto);
          }});
  	});

  });
}

function EnlargementOpen(popupPhoto) {
	// identify source
	//var popupPhoto = $('.popup_photo').getElement('img');
	var imgSource = popupPhoto.get("src");
	imgSource = imgSource.replace(".jpg", "_large.jpg");
	
	// show overlay
	$('enlarg_container').tween('opacity', [0, 0.7]);

	// show image placeholder
	var enlargImgcontainer = $('enlarg_imgcontainer');
	var size = window.getSize();
	enlargImgcontainer.setStyle("left", size.x/2);
	enlargImgcontainer.fade("in");

	// enlarge image placeholder
	var finalSize = size.y-100;
	if (finalSize>700) { finalSize=700; }

	var myEffect = new Fx.Morph(enlargImgcontainer, {duration: 'normal', transition: Fx.Transitions.Sine.easeOut});
	myEffect.start({
		'height': [150, finalSize+15],
		'width': [150, finalSize],
		'left': [(size.x/2), (size.x/2 - finalSize/2)],
		'top': [20, (size.y/2 - finalSize/2)-15]
	});

	// preload image
	var myImagePreloader = new Asset.image(imgSource);

	// load image with a delay
	var showImage= function(){ 
			// load image in place
			var enlImage = $('enlarg_image');
			enlImage.set("src", imgSource);
			enlImage.setStyle("width", finalSize);
			enlImage.setStyle("height", finalSize);
			enlImage.fade("in");	
			
			// close button
			$('enlarg_close').fade("in");
			$('enlarg_close').addEvent("click", function() {
					$('enlarg_image').fade("hide");		 
					$('enlarg_imgcontainer').fade("hide");
					$('enlarg_close').fade("hide");					
					$('enlarg_image').set("src", "images/blank.gif");
					$('enlarg_image').setStyle("width", "150px");
					$('enlarg_image').setStyle("height", "150px");
					$('enlarg_imgcontainer').setStyle("width", "150px");
					$('enlarg_imgcontainer').setStyle("height", "150px");
					$('enlarg_container').fade("out");
			});

	};
	showImage.delay(500, imgSource, finalSize); 
	
}

function enableSlr() {
	//preload large image
	//var myImagePreloader = new Asset.image('images/slr_camera.png');
	//$('slrproduct').
	
	//handle popups
	for (var i=1; i<9; i++) {
		
		$('pop'+i).fade("hide");	
		$('link'+i).i = i;
		$('link'+i).addEvent("click", function() {
					// close others
					for (var j=1; j<9; j++) {
						$('pop'+j).fade("hide");
					}
					// open popup
					var i = this.i;
					$('pop'+i).fade("in");
				
					var closeb = $('close'+i);
					closeb.i = i;
					//close button
					closeb.addEvent("mouseenter", function() {
							this.set('src', 'images/slr_close_over.png');
					}.bind(closeb))
					closeb.addEvent("mouseleave", function() {
							this.set('src', 'images/slr_close.png');
					}.bind(closeb))
					closeb.addEvent("click", function() {
							var i = this.i;
							$('pop'+i).fade("hide");
							this.removeEvents();
					}.bind(closeb))
		  });
	
	}
				
}

function showNewsDetails(productid) {
	var popupPanel = $('news_popup_container');

	var urlPath = "lib/getcontent.php?type=newsitem&id=" + productid + "&ie=" + ie;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			popupPanel.empty();
			popupPanel.adopt(html);
			
    	popupPanel.show();
    	popupPanel.fade('in');		

      if($('news_content')) {
    		makeScrollbar($('news_content'), $('news_scrollbar'), $('news_scrollhandle'));
      }
      
      if($('news_content') && $('news_gallery')) {
        $('news_popup_container').setStyle('width', '870px');
        $('news_popup_container').setStyle('left', '34px');
      } else
      if($('news_content')) {
        $('news_popup_container').setStyle('width', '595px');
        $('news_popup_container').setStyle('left', '190px');
      } else {
        $('news_popup_container').setStyle('width', '252px');
        $('news_popup_container').setStyle('left', '335px');
      } 

    	$('close_news').addEvent("click", function() {
    	  //$('news_popup_container').hide();
   	  	$('news_popup_container').fade('hide');

      });
      
      function mycarousel_initCallback(carousel) {
        JQ('.carousel_thumb').bind('click', function() {
          carousel.scroll(JQ.jcarousel.intval(JQ(this).attr("id").substring(6,7)));
          carousel.options.auto = 0;
          carousel.stopAuto();
          
          JQ('.carousel_thumb').removeClass('active');
          JQ(this).addClass('active');
          return false;
        });
      };

      function mycarousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
        JQ('.carousel_thumb').removeClass('active');
        JQ(".carousel_thumb" ).each(
        function( intIndex ){
          if(intIndex == (idx - 1)) {
            JQ(this).addClass('active');
          }
        });
      };

      if(JQ(".carousel_thumb" ).length < 6) {
        JQ('#thumb_carousel').jcarousel({
          scroll: 5,
          buttonNextHTML: null,
          buttonPrevHTML: null
        });
      } else {
        JQ('#thumb_carousel').jcarousel({
          scroll: 5
        });
      } 
      JQ('#photo_carousel').jcarousel({
        auto: 5,
        scroll: 1,
        wrap: 'last',
        initCallback: mycarousel_initCallback,
        itemVisibleInCallback: {
                    onAfterAnimation: mycarousel_itemVisibleInCallbackAfterAnimation
                }
      });

      enableLargePhotos();
      Slimbox.scanPage();
		}
	});
	req.send();

}


function repairHashUrl() {
  $$('a').each(function(el){
    if(el.get("href") == "#") {
      el.set("href", _pp.get());
    }
    if(el.get("href").test("#tab_.+", 'i')) {
      var match = /#tab_(.+)/i.exec(el.get("href"));
      var _pp2 = _pp;
      _pp2.setTab("");
      _pp2.polacz();
      el.set("href", _pp.get()+"/"+match[1]);
    }
  });
}

function enableAdmin() {
  	$('news_popup_container').fade('hide');

		makeScrollbar($('search_result_content'), $('search_result_scrollbar'), $('search_result_scrollhandle'));
		
		if($('news_search')) {
      $('news_search').addEvent("click", function() {
        news_search();
      });
      $('news_clear').addEvent("click", function() {
        $('news_keyword').set('value', '');
      });
      $('news_category').addEvent("change", function() {
        news_search();
      });
      $('news_keyword').addEvent("keydown", function(event) {
        if(event.key == 'enter') {
          news_search();
        }
      });
    }
		if($('product_search')) {
      $('product_search').addEvent("click", function() {
        product_search();
      });
      $('product_clear').addEvent("click", function() {
        $('product_modelnumber').set('value', '');
      });
      
      $('product_category').addEvent("change", function() {
        if($('product_category').get('value') > 0 && $('product_category').get('value') != 2) {
          $('product_subcategory').set('disabled', '');

    			var req = new Request.HTML({
    				url:"lib/getcontent_admin.php?type=subcategories", 
    				method:'get',
    				data:'product_category='+$('product_category').get('value'),
    				onSuccess: function(tree, elements, html) {
              $('product_subcategory').empty();
              $('product_subcategory').set('html', html);
    				}
    			});
    			req.send();  

          
          $('product_item').set('disabled', 'true');
          $('product_item').empty();
          $('product_item').set('html', '<option value="0" label="All">All</option>');
        } else {
    			var req = new Request.HTML({
    				url:"lib/getcontent_admin.php?type=items", 
    				method:'get',
    				data:'product_subcategory='+$('product_category').get('value'),
    				onSuccess: function(tree, elements, html) {
              $('product_item').set('disabled', '');
              $('product_item').empty();
              $('product_item').set('html', html);
    				}
    			});
    			req.send();  
        
          $('product_subcategory').set('disabled', 'true');
          $('product_subcategory').empty();
          $('product_subcategory').set('html', '<option value="0" label="All">All</option>');
        }
        product_search();
      });
      
      $('product_subcategory').addEvent("change", function() {
        if($('product_subcategory').get('value') > 0 && $('product_subcategory').get('value') != 2) {
          $('product_item').set('disabled', '');

    			var req = new Request.HTML({
    				url:"lib/getcontent_admin.php?type=items", 
    				method:'get',
    				data:'product_subcategory='+$('product_subcategory').get('value'),
    				onSuccess: function(tree, elements, html) {
              $('product_item').empty();
              $('product_item').set('html', html);
    				}
    			});
    			req.send();  

          
        } else {
          $('product_item').set('disabled', 'true');
          $('product_item').empty();
        }
        product_search();
      });
      
      $('product_item').addEvent("change", function() {
        product_search();
      });
      
      $('product_modelnumber').addEvent("keydown", function(event) {
        if(event.key == 'enter') {
          product_search();
        }
      });
    }



}	

      function product_search() {           
  			var req = new Request.HTML({
  				url:"lib/getcontent_admin.php?type=product_search", 
  				method:'post',
  				data:'product_category='+$('product_category').get('value')+'&product_subcategory='+$('product_subcategory').get('value')+'&product_item='+$('product_item').get('value')+'&product_modelnumber='+$('product_modelnumber').get('value'),
  				onSuccess: function(html) {
            $('search_result_content').empty();
            $('search_result_content').adopt(html);
        		makeScrollbar($('search_result_content'), $('search_result_scrollbar'), $('search_result_scrollhandle'));
  				}
  			});
  			req.send();  
      }



function delProduct(productid) {
	var popupPanel = $('news_popup_container');

	var urlPath = "lib/getcontent_admin.php?type=delproduct&prodid=" + productid;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
		  product_search();
		}
	});
	req.send();

}






      function news_search() {           
  			var req = new Request.HTML({
  				url:"lib/getcontent_admin.php?type=news_search", 
  				method:'post',
  				data:'news_category='+$('news_category').get('value')+'&keyword='+$('news_keyword').get('value'),
  				onSuccess: function(html) {
            $('search_result_content').empty();
            $('search_result_content').adopt(html);
        		makeScrollbar($('search_result_content'), $('search_result_scrollbar'), $('search_result_scrollhandle'));
  				}
  			});
  			req.send();  
      }


function editNews(productid) {
	var popupPanel = $('news_popup_container');

	var urlPath = "lib/getcontent_admin.php?type=newsitem&id=" + productid;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			popupPanel.empty();
			popupPanel.adopt(html);
			
    	popupPanel.show();
    	popupPanel.fade('in');		

      if($('news_content') && !$('admin_container')) {
    		makeScrollbar($('news_content'), $('news_scrollbar'), $('news_scrollhandle'));
      }
      
      $('news_popup_container').setStyle('width', '870px');
      $('news_popup_container').setStyle('left', '160px');
      $('news_popup_container').setStyle('background-color', '#000000');

    	$('admin_button_back').addEvent("click", function() {
    	  //$('news_popup_container').hide();
   	  	$('news_popup_container').fade('hide');

      });
      

      var myCal = new Calendar({edit_news_date: 'Y-m-d'}, { classes: ['dashboard']});
      
      var editor;
      
      function createEditor()
      {
      	if ( editor )
      		return;
      
      	var html = document.getElementById( 'editor_content' ).innerHTML;
      
      	// Create a new editor inside the <div id="editor">, setting its value to html
      	var config = {
//      	  toolbar : 'Basic',
          toolbar : [
            ['Format','Font','FontSize'],
            ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link'],
            ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
            ['Source'],['Maximize']
          ],
      	  height: 240,
          filebrowserUploadUrl : 'upload.php',
          filebrowserImageUploadUrl : 'upload.php?type=Images'
        };
      	editor = CKEDITOR.appendTo( 'editor', config, html );
      }
      
      createEditor();

    	$('admin_button_save').addEvent("click", function() {
      	var urlPath = "lib/getcontent_admin.php?type=savenewsitem&id=" + productid;
      	var req2 = new Request.HTML({
      		url:urlPath, 
      		method:'post',
          data:{
            category : $('edit_news_category').get('value'),
            title : $('edit_news_title').get('value'),
            date : $('edit_news_date').get('value'),
            content : editor.getData()
          },
      		onSuccess: function(html) {
       	  	$('news_popup_container').fade('hide');
       	  	showNewsDetails(productid);
            news_search();
          }
        });
        req2.send();
      });



		}
	});
	req.send();

}

function addNews() {
	var popupPanel = $('news_popup_container');

	var urlPath = "lib/getcontent_admin.php?type=addnews";
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			popupPanel.empty();
			popupPanel.adopt(html);
			
    	popupPanel.show();
    	popupPanel.fade('in');		

      if($('news_content') && !$('admin_container')) {
    		makeScrollbar($('news_content'), $('news_scrollbar'), $('news_scrollhandle'));
      }
      
      $('news_popup_container').setStyle('width', '870px');
      $('news_popup_container').setStyle('left', '160px');
      $('news_popup_container').setStyle('background-color', '#000000');

    	$('admin_button_back').addEvent("click", function() {
    	  //$('news_popup_container').hide();
   	  	$('news_popup_container').fade('hide');

      });
      

      var myCal = new Calendar({edit_news_date: 'Y-m-d'}, { classes: ['dashboard']});
      
      var editor;
      
      function createEditor()
      {
      	if ( editor )
      		return;
      
      	var html = document.getElementById( 'editor_content' ).innerHTML;
      
      	var config = {
          toolbar : [
            ['Format','Font','FontSize'],
            ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link'],
            ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
            ['Source'],['Maximize']
          ],
      	  height: 240,
          filebrowserUploadUrl : 'upload.php',
          filebrowserImageUploadUrl : 'upload.php?type=Images'
        };
      	editor = CKEDITOR.appendTo( 'editor', config, html );
      }
      
      createEditor();

    	$('admin_button_save_new').addEvent("click", function() {
      	var urlPath = "lib/getcontent_admin.php?type=addnewsitem";
      	var req2 = new Request.HTML({
      		url:urlPath, 
      		method:'post',
          data:{
            category : $('edit_news_category').get('value'),
            title : $('edit_news_title').get('value'),
            date : $('edit_news_date').get('value'),
            content : editor.getData()
          },
      		onSuccess: function(html) {
       	  	$('news_popup_container').fade('hide');
       	  	showNewsDetails(html.item(0).nodeValue.toInt());
 	  	      news_search();
          }
        });
        req2.send();
      });



		}
	});
	req.send();

}

function delNews(productid) {
	var popupPanel = $('news_popup_container');

	var urlPath = "lib/getcontent_admin.php?type=delnewsitem&id=" + productid;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
		  news_search();
		}
	});
	req.send();

}

var MyEditor = new Class({
  editor : null,
  set : function(editor) {
    this.editor = editor;
  },
  get : function() {
    return this.editor;
  }
});
var overview_editor = new MyEditor();
var techspecs_editor = new MyEditor();
                          
function editProduct(productid) {
	var popupPanel = $('news_popup_container');



	var urlPath = "lib/getcontent_admin.php?type=proddetails&prodid=" + productid;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			popupPanel.empty();
			popupPanel.adopt(html);
			
    	popupPanel.show();
    	popupPanel.fade('in');		

      $('news_popup_container').setStyle('width', '870px');
      $('news_popup_container').setStyle('left', '160px');
      $('news_popup_container').setStyle('background-color', '#000000');
      
      
      var tabPane = new TabPane("admin_product_details_tabs", {
        tabSelector: "a.tab_sel",
        contentSelector: "div.tab_tab"
      });

      JQ("input.file_1").filestyle({ 
          image: "images/button_browse.png",
          imageheight : 18,
          imagewidth : 65,
          width : 200
      });
      JQ("input.file_2").filestyle({ 
          image: "images/button_browse.png",
          imageheight : 18,
          imagewidth : 65,
          width : 200
      });
      JQ("input.file_3").filestyle({ 
          image: "images/button_browse.png",
          imageheight : 18,
          imagewidth : 65,
          width : 200
      });

     
      function createEditor(eds, editor_id, content)
      {
      
      	var html = document.getElementById( content ).innerHTML;
      
      	var config = {
          toolbar : [
            ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link'],
            ['Image','Table','HorizontalRule','SpecialChar'],
            ['Source']
          ],
      	  height: 255,
          filebrowserUploadUrl : 'upload.php',
          filebrowserImageUploadUrl : 'upload.php?type=Images'
        };
        config.forcePasteAsPlainText = true;
      	eds.set(CKEDITOR.appendTo( editor_id, config, html ));
      	document.getElementById( content ).style.display = 'none';
      }

      function removeEditor(editor, content)
      {
      	if ( !editor )
      		return;
      
      	// Retrieve the editor contents. In an Ajax application, this data would be
      	// sent to the server or used in any other way.
      	document.getElementById( content ).innerHTML = editor.getData();
      	document.getElementById( content ).style.display = '';
      
      	// Destroy the editor.
      	editor.destroy();
      	editor = null;
      }
      
      createEditor(overview_editor, 'overview_editor', 'prod_edit_overview');
      createEditor(techspecs_editor, 'techspecs_editor', 'prod_edit_techspecs');


      $('prod_edit_category').addEvent("change", function() {
        if($('prod_edit_category').get('value') > 0 && $('prod_edit_category').get('value') != 2) {

    			var req = new Request.HTML({
    				url:"lib/getcontent_admin.php?type=subcategories&noall=1", 
    				method:'get',
    				data:'product_category='+$('prod_edit_category').get('value'),
    				onSuccess: function(tree, elements, html) {
              $('prod_edit_subcategory').empty();
              $('prod_edit_subcategory').set('html', html);
    				}
    			});
    			req.send();  

        } else {
          $('prod_edit_subcategory').empty();
          $('prod_edit_subcategory').set('html', '<option value="0" label="---">---</option>');
        }
      });


    	$('prod_edit_button_back').addEvent("click", function() {
   	  	$('news_popup_container').fade('hide');
      });

    	$('prod_edit_button_save').addEvent("click", function() {
      	var urlPath = "lib/getcontent_admin.php?type=saveproduct&id=" + productid;
      	
      	
      	var req2 = new Request.HTML({
      		url:urlPath, 
      		method:'post',
          data:{
            category : $('prod_edit_category').get('value'),
            subcategory : $('prod_edit_subcategory').get('value'),
            name : $('prod_edit_name').get('value'),
            fullname : $('prod_edit_fullname').get('value'),
            mpixels : $('prod_edit_mpixels').get('value'),
            warranty : $('prod_edit_warranty').get('value'),
            active : $('prod_edit_active').get('value'),
            overview : overview_editor.get().getData(),            
            techspec : techspecs_editor.get().getData()            
          },
      		onSuccess: function(html) {                        
       	  	$('news_popup_container').fade('hide');
            product_search();
          }
        });
        req2.send();
      });



		}
	});
	req.send();

}

function addProduct() {
	var popupPanel = $('news_popup_container');



	var urlPath = "lib/getcontent_admin.php?type=newproduct";
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			popupPanel.empty();
			popupPanel.adopt(html);
			
    	popupPanel.show();
    	popupPanel.fade('in');		

      $('news_popup_container').setStyle('width', '870px');
      $('news_popup_container').setStyle('left', '160px');
      $('news_popup_container').setStyle('background-color', '#000000');
      
      
      var tabPane = new TabPane("admin_product_details_tabs", {
        tabSelector: "a.tab_sel",
        contentSelector: "div.tab_tab"
      });


     
      function createEditor(eds, editor_id, content)
      {
      
      	var html = document.getElementById( content ).innerHTML;
      
      	var config = {
          toolbar : [
            ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link'],
            ['Image','Table','HorizontalRule','SpecialChar'],
            ['Source']
          ],
      	  height: 255,
          filebrowserUploadUrl : 'upload.php',
          filebrowserImageUploadUrl : 'upload.php?type=Images'
        };
        config.forcePasteAsPlainText = true;
      	eds.set(CKEDITOR.appendTo( editor_id, config, html ));
      	document.getElementById( content ).style.display = 'none';
      }

      function removeEditor(editor, content)
      {
      	if ( !editor )
      		return;
      
      	// Retrieve the editor contents. In an Ajax application, this data would be
      	// sent to the server or used in any other way.
      	document.getElementById( content ).innerHTML = editor.getData();
      	document.getElementById( content ).style.display = '';
      
      	// Destroy the editor.
      	editor.destroy();
      	editor = null;
      }
      
      createEditor(overview_editor, 'overview_editor', 'prod_edit_overview');
      createEditor(techspecs_editor, 'techspecs_editor', 'prod_edit_techspecs');


      $('prod_edit_category').addEvent("change", function() {
        if($('prod_edit_category').get('value') > 0 && $('prod_edit_category').get('value') != 2) {

    			var req = new Request.HTML({
    				url:"lib/getcontent_admin.php?type=subcategories&noall=1", 
    				method:'get',
    				data:'product_category='+$('prod_edit_category').get('value'),
    				onSuccess: function(tree, elements, html) {
              $('prod_edit_subcategory').empty();
              $('prod_edit_subcategory').set('html', html);
    				}
    			});
    			req.send();  

        } else {
          $('prod_edit_subcategory').empty();
          $('prod_edit_subcategory').set('html', '<option value="0" label="---">---</option>');
        }
      });


    	$('prod_edit_button_back').addEvent("click", function() {
   	  	$('news_popup_container').fade('hide');
      });

    	$('prod_edit_button_save_new').addEvent("click", function() {
      	var urlPath = "lib/getcontent_admin.php?type=savenewproduct";
      	
      	
      	var req2 = new Request.HTML({
      		url:urlPath, 
      		method:'post',
          data:{
            category : $('prod_edit_category').get('value'),
            subcategory : $('prod_edit_subcategory').get('value'),
            name : $('prod_edit_name').get('value'),
            fullname : $('prod_edit_fullname').get('value'),
            mpixels : $('prod_edit_mpixels').get('value'),
            warranty : $('prod_edit_warranty').get('value'),
            active : $('prod_edit_active').get('value'),
            overview : overview_editor.get().getData(),            
            techspec : techspecs_editor.get().getData()            
          },
      		onSuccess: function(html) {                        
       	  	$('news_popup_container').fade('hide');
            editProduct(html.item(0).nodeValue.toInt());
            product_search();
          }
        });
        req2.send();
      });



		}
	});
	req.send();

}

function loadFiles(id) {
	var urlPath = "lib/getcontent_admin.php?type=file_list&prodid=" + id;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(tree, elements, html) {
      $('file_list').empty();
      $('file_list').set('html', html);
		}
	});
	req.send();

}

function removeFile(id, file) {
//	var popupPanel = $('news_popup_container');

	var urlPath = "lib/getcontent_admin.php?type=removefile&file=" + file;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
		  //news_search();
		  loadFiles(id);
		}
	});
	req.send();

}

function loadPhotos(id) {
	var urlPath = "lib/getcontent_admin.php?type=photo_list&prodid=" + id;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(tree, elements, html) {
      $('photo_list').empty();
      $('photo_list').set('html', html);
      
      $('upload_photo').set('value', '');
      $('upload_photo2').set('value', '');
		}
	});
	req.send();

}


function photoValid() {
  if($('upload_photo').get('value') == '' || $('upload_photo2').get('value') == '') {
    $('photo_error').set('html', 'You must select both files before you can upload');
    $('photo_error').show();
    return false;
  } else {
    $('photo_error').hide();
    return true;
  }
}

function uploadPhotoError(id) {
  if($('photo_error')) {
    $('photo_error').set('html', id);
    $('photo_error').show();
  }
}
function uploadFileError(id) {
  if($('file_error')) {
    $('file_error').set('html', id);
    $('file_error').show();
  }
}

//function uploadFileError(id) {
//  alert(id);
//}

function deletePhoto(id, photo_id/*file*/) {
//	var popupPanel = $('news_popup_container');

	var urlPath = "lib/getcontent_admin.php?type=removephoto&photo_id=" + photo_id;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
		  //news_search();
		  loadPhotos(id);
		}
	});
	req.send();

}

function swapPhoto(id, photo_id, o1, photo_id2, o2) {
//	var popupPanel = $('news_popup_container');

	var urlPath = "lib/getcontent_admin.php?type=swapphotos&photo_id1=" + photo_id + "&order1=" + o1 + "&photo_id2=" + photo_id2 + "&order2=" + o2;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
		  //news_search();
		  loadPhotos(id);
		}
	});
	req.send();

}

