// JavaScript Document
var core = {};
var IOS = window.navigator.userAgent.match(/iPhone|iPad|iPod/ig) ? true : false;
var IE = window.navigator.userAgent.match(/MSIE 6|MSIE 7|MSIE 8/ig) ? true : false;

function showhide(o,st)
{
 if (typeof(o)=="string")
 {
  o=document.getElementById(o);
 }
 if (!o)
 {
  return;
 }
 if (typeof(st)!="boolean")
 {
  st=(o.style.display=="none");
 }
 o.style.display=(st) ? "" : "none";
 return st;
}

function menuToggle(tab){
	var NumTabs = 13;
	var item_num = tab.substr(2,2);
	for (i=1; i<=NumTabs; i++)
	{
		var m = document.getElementById('m_'+ i);
		var sm = document.getElementById('sm_'+ i);
		if (i==item_num)
		{
		m.className = (m.className=="") ? "active" : "";
		sm.className = (sm.className=="subnav") ? "subnav hide" : "subnav";
		}
		else
		{
		m.className = "";
		sm.className = "subnav hide";
		}
	}
}

function updatequant(quan, whichbox, minamount)
	{
		newquant = parseFloat(whichbox.value) + quan;
		
		if(newquant < minamount && quan == -1){
			newquant = 0;
		}

		if(newquant < minamount && quan == 1){
			newquant = minamount;
		}

		if (newquant >= 0){
			whichbox.value = newquant;
		}
	}
	
function updatebasket() {	
	document.getElementById("ubasket").submit();
}
	
	
	
function popup(url,winname,w,h,feat) {
	if (!(isNaN(w) || isNaN(h)))
	{
		var x=parseInt((screen.width-w)/2);
		var y=parseInt((screen.height-h)/2);
		if (x<0)	x=0;
		if (y<0)	y=0;
		
		if (feat!=null && feat!="")
		{
			feat=","+feat;
		}
		else
		{
			feat="";
		}
		feat="left="+x+",top="+y+",width="+w+",height="+h+feat;
	}
	window.open(url,winname,feat);
}

function openTerms() {
	popup(dotdotpath+"terms/","terms",500,500,"scrollbars=1");
}
function openTermsSkip() {
	popup(dotdotpath+"terms/index.cfm#genconditions","terms",500,500,"scrollbars=1");
}
function openTermsOrder() {
	popup(dotdotpath+"orderingterms/index.cfm","terms",500,500,"scrollbars=1");
}

function openEnvironmental() {
	popup(dotdotpath+"environmental/","environmental",500,500,"scrollbars=1");
}

function setActiveLink(where,which){
	var div = document.getElementById(where);
	var lnkid = which.substr(3,2);
	var links = div.getElementsByTagName("a");
	var numlinks = links.length;
	
	for(i=1; i<=numlinks; i++){
		var m = document.getElementById('fr_'+ i);
		if(i==lnkid){
			m.className = "active";
		}else{
			m.className="";
		}
	}
}


function useSameAddress(){
	document.getElementById("deliveryid").value="";
	if(document.getElementById("companyname").value.length == 0){
		document.getElementById("delivery_companyname").value = document.getElementById("forename").value + " " + document.getElementById("surname").value;
	} else {
		document.getElementById("delivery_companyname").value = document.getElementById("companyname").value;
	}
							   
	document.getElementById("delivery_address1").value = document.getElementById("address1").value;
	document.getElementById("delivery_address2").value = document.getElementById("address2").value;
	document.getElementById("delivery_address3").value = document.getElementById("address3").value;
	document.getElementById("delivery_town").value = document.getElementById("town").value;
	document.getElementById("delivery_postcode").value = document.getElementById("postcode").value;
}

function bookmarksite(title,url){
	if(bookmarkname !=""){
	   var title = "Gopak UK - Homepage"; 
	}else{
		var title = document.title; 
	}
	
    var url = window.location.href;
 if (window.sidebar) // firefox
    // window.sidebar.addPanel(title, url, ""); //Dont use until it's fixed
    alert('please press CTRL+D to Bookmark this page!');
else if(window.opera && window.print){ // opera
     var elem = document.createElement('a');
    elem.setAttribute('href',url);
     elem.setAttribute('title',title);
     elem.setAttribute('rel','sidebar');
    elem.click();
 } 
else if(document.all)// ie
     window.external.AddFavorite(url, title);
}
 
 
// core ui classes -------------------------------

function extendClass(cla,methods,parent){
	cla.prototype = new parent({});
	cla.prototype.constructor = cla;
	for( prop in methods ){cla.prototype[prop] = methods[prop];}
}
 
Slider = function(opts){
	if(!opts.wrap){ return false; }
	var t = this, bn = opts.next || '.next',bp = opts.prev || '.prev',pagingWrap = opts.pagingWrap || '.paging',scroller = opts.scroller || 'div.scroll', items = opts.items || 'ul.items > li';

	this.index = 0; this.row = opts.row || 1; this.offset = opts.offset || 0; this.speed = opts.speed || 200;
	this.wrap = $(opts.wrap);
	this.mask = this.wrap.find('div.mask');
	this.scroller = this.wrap.find(scroller);
	this.items = this.scroller.find(items);
	this.total = Math.ceil(this.items.length / this.row);
	this.btn_next = this.wrap.find(bn);
	this.btn_prev = this.wrap.find(bp);
	this.pagingNav = this.wrap.find(pagingWrap);
	this.auto = opts.auto || false;
	this.touch = opts.touch || true;
	this.cb = opts.cb || function(){};
	this.parent = opts.parent || false;
	
	(function(t){
		t.bindTouch();t.init();t.layout();	
		t.btn_next.click( function(){ t.stop(); t.next();return false;} );
		t.btn_prev.click( function(){ t.stop(); t.prev();return false;} );
		
		//t.auto ? t.timer = setInterval(function(){ t.next(); },t.auto) : '';
		if( t.pagingNav.length ) { t.initPaging(); }
		t.setBtnStatus();
	})(this); 
	return t;
}
Slider.prototype = {
	layout:function(){
		var t = this, ma = t.mask.width(), m = (t.row-1)*(t.offset*2);
		var w = t.row > 1 ? (ma - m) / t.row : ma;
		t.items.css({float:'left',marginLeft:t.offset,marginRight:t.offset,width:w });
		t.itemW = t.items.outerWidth(true) * t.row;
		t.scroller.width(t.items.length/t.row * t.itemW );
		t.scroller.css({marginLeft:-t.offset});	
		
		t.parent && !t.pagingNav ? t.parent.setHeight() : '';
	},
	getIndex:function (){
		if( this.index <=0 ){ this.index = 0 }
		else if(this.index > this.total - 1 ) { this.auto ? this.index = 0 : this.index = this.total-1 }
		return this.index;
	},
	bindTouch:function(){},
	init:function(){ },
	next:function(){ this.index++;this.goTo(this.getIndex()); },
	prev:function(){ this.index--;this.goTo(this.getIndex()); },
	stop:function(){ if(this.auto) { clearInterval(this.timer); this.auto = false; }; },
	play: function(){ var t = this; t.auto ? t.timer = setInterval(function(){ t.next(); },t.auto) : ''; },
	aMove:function(n){ var t = this; this.scroller.animate({left: -this.itemW * n},this.speed,function(){ t.cb();t.setActive()} );},
	goTo:function(n){ this.aMove(n);this.index = parseInt(n);this.setBtnStatus();},
	initPaging: function(){
		if(this.total == 1){ this.pagingNav.html('').hide(); return false;}
		var pi = '<ul class="sliderPaging">',t=this;
		if(this.total > 1){
			for(var i=0; i<this.total; i++){ pi+='<li><a href="#"><span>'+parseInt(i)+'</span></a></li>';}
			this.pagingNav.html(pi+'</ul>');
			this.pagingLinks = this.pagingNav.find('a');
			this.pagingLinks.click(function(){ t.stop();t.goTo( $(this).find('span').text() ); return false; })
			this.setActive();
		}
		t.parent ? t.parent.setHeight() : '';
	},
	setActive: function(){
		var pl = this.pagingLinks || [];
		if(pl.length){ pl.removeClass('active').slice(this.index,this.index+1).addClass('active'); }
	},
	setBtnStatus:function(){
		if( this.index == 0 ){ this.btn_prev.addClass('disabled');this.btn_next.removeClass('disabled'); if(this.total == 1){this.btn_next.addClass('disabled')} }
		else if(this.index >= this.total -1 ){ this.btn_next.addClass('disabled');this.btn_prev.removeClass('disabled'); }
		else { this.btn_prev.add(this.btn_next).removeClass('disabled'); }
	},
	reInit: function(sliderIndex){
		var n = sliderIndex || this.getIndex(), t = this;
		this.items = this.scroller.find('.item').css({float:'left',margin:'0 '+t.offset+'px'});
		this.itemW = this.items.outerWidth(true) * this.row;
		this.total = Math.ceil(this.items.length / this.row);
		this.scroller.width( this.total * this.itemW );
		if( n === 'first' ){ n = 0 }
		this.goTo(n);
		if( this.pagingNav.length ) { this.initPaging(); }
		this.setBtnStatus();
	}
}
if(IOS){
	Slider.prototype.aMove = function(n){
		var t = this;
		this.scroller[0].style.webkitTransition = t.speed*2+'ms ease';
		this.scroller[0].style.webkitTransform = 'translate3d('+-t.itemW*n+'px,0,0)';
		this.scroller.one('webkitTransitionEnd',function(){ transitionEnd(this); });
		
		function transitionEnd(ele){
			t.getPosition(ele.style.webkitTransform);
			ele.style.webkitTransition = '';
			t.setActive();
		}
	}
	Slider.prototype.getPosition = function(transform){
		var v = transform.replace(/[a-z]/g,'').replace('3(','').replace(')','').split(',') || [0,0,0];
		this.x = parseInt(v[0]); this.y = v[1];
	}
	Slider.prototype.bindTouch = function(){
		if(!this.scroller.length){ return false; }
		var t = this;
		//console.log(this.constructor.name,this.touch);
		if(this.touch){
			this.scroller[0].ontouchstart = function(e){ t.onTouchStart(e); }
			this.scroller[0].ontouchmove = function(e){ t.onTouchMove(e); }
			this.scroller[0].ontouchend = function(e){ t.onTouchEnd(e); }
			//this.goTo(0);
			this.getPosition(this.scroller[0].style.webkitTransform);
		}
	}
	Slider.prototype.move = function(x,y){
		var newX = parseInt(this.x+x);
		this.scroller[0].style.webkitTransform = 'translate3d('+newX+'px,0,0)';
	}
	Slider.prototype.onTouchStart = function(e){
		var t = this;
		this.auto ? this.stop() : '';
		if (e.targetTouches.length != 1) {return false;}
		this.scroller[0].style.webkitTransition = '';
		this.startX = e.targetTouches[0].clientX;
		this.cTouch = this.startX;
		this.startY = e.targetTouches[0].clientY;
		this.getPosition(this.scroller[0].style.webkitTransform);
		
	}
	Slider.prototype.onTouchMove = function(e) {
		//e.preventDefault();
		if (e.targetTouches.length != 1) { return false; }
		var leftDelta = e.targetTouches[0].clientX - this.startX;
		var topDelta = e.targetTouches[0].clientY - this.startY;
		//if( topDelta > -5 || topDelta < 5 ){ e.preventDefault(); }
		this.move(leftDelta,0);
		this.cTouch = e.targetTouches[0].clientX;
	}
	Slider.prototype.onTouchEnd = function(e){
		var t =this, difX = this.startX - this.cTouch, limit = t.mask.width()*0.3;
		e.preventDefault();
		if (e.targetTouches.length > 0) { return false; }
		if(difX > limit){this.next();}
		else if( difX < -limit ){ this.prev(); }
		else {this.goTo(this.getIndex());}
	}
} // /if IOS

function Banner(opts){
	this.xml = opts.xml || false;
	this.loading = true;
	Slider.call(this,opts);
	this.cb = function(){
		var t = this, title = t.item_data[t.index].title;
	}
}
var bannerMethods = {
	init:function(){
		var t = this;
		//get xml
		$.ajax({
			url:t.xml,
			success:function(data){
				t.item_data = getItems(data);
				setItems();
				t.reInit();
			}
		});
		function getItems(feed){
			var f_items = $(feed).find('items').find('item') || false, len = f_items ? f_items.length : 0,items=[];
			for(var i = 0;i<len;i++){
				var f = $(f_items[i]);
				items[i]={src:f.find('src').text(),href:f.find('link').text(),title:f.find('title').text()}
			}
			return items;
		}
		function setItems(items){
			var d = items || t.item_data,len = d.length,mu='',img = new Image();
			for(var i=0;i<len;i++){
				mu+='<div class="item">'+setLink(d[i])+'<img src="'+d[i].src+'" /></div>';
			}
			t.scroller.html(mu);
			img.onload = function(){ t.loader() }
			img.src = d[0].src;
			
			
			function setLink(obj){
				var title = obj.title;
				return title !=='' ? '<a class="cta_gry" href="'+obj.href+'"><span class="l"></span><span class="rpt">'+title+'</span><span class="r"></span></a>' : '';
			}
		}
	},
	loader:function(show){
		var s = show || false;
		!s ? this.wrap.removeClass('loading') : this.wrap.addClass('loading');
		this.wrap.hasClass('loading') ? this.loading = true : this.loading = false;
		!this.wrap.hasClass('loading') && !this.loading ? this.play() : ''; 
	}
}
extendClass(Banner,bannerMethods,Slider);

function Videos(opts){
	this.id = 'video';
	this.dotdotpath = opts.dotdotpath || '';
	//(function(t){ t.init(); })(this)
}
Videos.prototype = {
	init:function(){ 
		//console.log(SWFobject);
		var t = this, b = $(document.getElementsByTagName('body'));
		b.append('<div id="'+t.id+'">Video content</div>');
		t.wrapper = $('#'+t.id);
	},
	open:function(path){
		if(!path){ return false; }
		var t = this;
		var html ='<div id="video"><video controls ><source src="'+t.dotdotpath+'media/mp4/'+path+'.mp4" type="video/mp4" /></video></div>'
		$.colorbox({
			html:html,
			width:690,
			height:360,
			speed:200,
			onComplete:function(){
				swfobject.embedSWF(t.dotdotpath+'flash/videoplayer.swf', 'video', '640', '360', '9.0.115', '',
					{
						src: '../media/flv/'+path+'.flv',
						innerWidth: 640,
						innerHeight: 410,
						autoStart: 'false',
						scaleMode: 'fit',
						hideControls: 'false',
						mode: 'overlay'
					},
					{allowfullscreen: 'true', allowscriptaccess: 'always', bgcolor: '#d7d7d7', wmode: 'opaque', scale: "noScale"},
					{id: 'video'}
				);
				$.colorbox.resize();
			}
		});
	}
}




