
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

var cartText = '';
cartText += '<div id="cart_header"><img onclick="showHide(\'cart_div\')" src="sablons/cms/pics/minimalize.jpg"/><img onclick="showHide(\'cart_layer\')" class="close" src="sablons/cms/pics/close.jpg"/></div><div style="display: block;" id="cart_div">';
cartText += '<div class="cart_products"><div class="cart_list"><div class="cart_product"><div class="delete">&nbsp;</div><div class="prod_name_text">Megnevezés</div><div class="prod_value_text"><span class="prod_price_1">Összeg</span><span class="prod_count">db</span></div></div>';
cartText += '<div id="cart_prod_list" class="prod_list">{prod_list}</div></div><div>Kérem várjon...</div><div id="fullcart_link"><a href="?l1=webstore&amp;l2=plug_webstore_cart&amp;l3=main">Kosár szerkesztése>></a></div></div></div>';

var cartProdText = '<div class="cart_product"><div class="delete"><div class="cart_button"><a class="addOneProduct" onclick="return editCart({pid}, \'removeFromCart\', {count}, 1)" title="Töröl" href="delAll">X</a></div></div><div class="prod_name_text"><a title="{text}" href="{link}"><span class="marka">{marka}&nbsp;</span><span class="tipus">{tipus}</span></a></div><div class="prod_value_text"><span class="prod_price_1">{ar}</span><span class="prod_count">x {count}db</span></div></div>';

function creatCartProdText() {
	pids = readCookie('tc_pids');
	ret = '';
	if ( pids ) {
		pids_temp = pids.split('_');
		for(i=0;i<pids_temp.length;i++) {
			pid = pids_temp[i];
			count = readCookie(pid+'_count');
			price = readCookie(pid+'_price');
			text  = readCookie(pid+'_text');
			link  = readCookie(pid+'_link');
			marka = '';
			tipus = '';
			text_t = text.split(' ');
			for(j=0;j<text_t.length;j++) {
				if ( j==(text_t.length-1)) {
					tipus += text_t[j];
				} else {
					marka += text_t[j];
				}
			}

			replaceText = cartProdText;
			replaceText = replaceText.replace('{pid}',pid);
			replaceText = replaceText.replace('{count}',count);
			replaceText = replaceText.replace('{count}',count);
			replaceText = replaceText.replace('{text}',text);
			replaceText = replaceText.replace('{marka}',marka);
			replaceText = replaceText.replace('{link}',link);
			replaceText = replaceText.replace('{tipus}',tipus);
			replaceText = replaceText.replace('{ar}',price);
			ret += replaceText;
		}
	}
	return ret;
}

function jsShowCart() {
	pids = readCookie('tc_pids');
	if ( pids ) {
		$('cart_layer').innerHTML = cartText.replace('{prod_list}',creatCartProdText());
		initCartPos();
	} else {
		$('cart_layer').style.display = 'none';
	}
}

function initCartPos() {
	$('cart_layer').style.display = 'block';
	if ( startInit ) {
		if ( readCookie('cartPost') ) {
			cPos = readCookie('cartPost').split(' ');
			$('cart_layer').style.left = cPos[0];
			$('cart_layer').style.top = cPos[1];
		} else {
			startInit = 0;
			if ( window.innerHeight ) {
				winH = window.innerHeight;
			} else {
				winH = document.documentElement.clientHeight;
			}
			hplusz = readCookie('tc_pids').split('_').length * 21;
			$('cart_layer').style.top = winH - Math.max(140+hplusz, $('cart_layer').offsetHeight - 25) + 'px';
		}
	}
}

var startInit = 1;
function showCart() {
	if ( $('cart_layer') ) {
		$('cart_layer').innerHTML = '';
		jsShowCart();
		tstamp = Number(new Date());
		new Ajax.Request( '?l1=webstore&l2=plug_webstore_cart&l3=main&ajax=1&time='+tstamp, {
				method: 'get',
				onSuccess: function(new_c) {
					if ( ( new_c.responseText ) && ( new_c.responseText.indexOf('static_content') == -1 ) ) {
						$('cart_layer').innerHTML = new_c.responseText;
						initCartPos();
					} else {
						$('cart_layer').style.display = 'none';
					}
				}
			}
		);
	}
}

function saveCookieData(pid) {
	pids = readCookie('tc_pids');
	if ( !pids || pids=='null' ) {
		pids = pid
	} else if ( pids.indexOf(pid) == -1 ) {
		pids += '_'+pid
	}
	createCookie('tc_pids',pids,0);
	createCookie(pid+'_text',$('name_v_'+pid).value,0);	createCookie(pid+'_price',$('price_v_'+pid).value,0);
	createCookie(pid+'_count',$('incart_num_'+pid).value,0);
	createCookie(pid+'_link',location,0);
}

function deleteCookieData(pid) {
	pids = readCookie('tc_pids');
	if ( pids && pids.indexOf(pid) != -1 ) {
		pids_temp = pids.split('_');
		new_pids = new Array();
		j=0;
		for(i=0;i<pids_temp.length;i++) {
			if (pids_temp[i]!=pid) {
				new_pids[j++] = pids_temp[i];
			}
		}
		createCookie('tc_pids',new_pids.join('_'),0);
		eraseCookie(pid+'_price')
		eraseCookie(pid+'_count')
		eraseCookie(pid+'_text')
		eraseCookie(pid+'_link')
	}
}

function manageCookieData(pid, count, type) {
	if ( type == 'removeFromCart' ) {
		count = readCookie(pid+'_count')-count;
	}
	if ( count && count>0 ) {
		saveCookieData(pid);
	} else {
		deleteCookieData(pid);
	}
}

function editCart( pid, type, count, run ) {

	if ( count > 0 ) {
		count_text = '&count='+count;
	} else {
		count_text = '';
	}

	if ( $('cart_layer') ) {
		if ( run ) {
			manageCookieData(pid, count, type);
			jsShowCart();
			new Ajax.Request( '?l1=webstore&l2=plug_webstore_cart&l3='+type+'&pid='+pid+count_text, {
					method: 'get',
					onSuccess: function(new_c) {
						if ( $('incart_num_'+pid) ) {
							$('incart_num_'+pid).value = new_c.responseText;
						}
						showCart();
						manageCookieData(pid, count, type);
					}
				}
			);
		} else {
			if ( type == 'removeFromCart' ) {
				manageCookieData(pid, count, type);
				$('incart_num_'+pid).value = Math.max(0, $('incart_num_'+pid).value-1 )*1;
			} else
			if ( type == 'addToCart' ) {
				manageCookieData(pid, count, type);
				$('incart_num_'+pid).value = ( $('incart_num_'+pid).value )*1+1;
			}
		}
	} else {
		new Ajax.Request( '?l1=webstore&l2=plug_webstore_cart&l3='+type+'&pid='+pid+count_text, {
				method: 'get',
				onSuccess: function(new_c) {
					new Ajax.Updater('full_cart_layer', '?l1=webstore&l2=plug_webstore_cart&l3=main&fullcart=1', { method: 'get' });
				}
			}
		);
	}

	return false;
}

/* DRAG AND DROP */
var _startX = 0; // mouse starting positions
var _startY = 0;
var _offsetX = 0; // current element offset
var _offsetY = 0;
var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove
var _oldZIndex = 0; // we temporarily increase the z-index during drag
//var _debug = $('debug'); // makes life easier

InitDragDrop();
function InitDragDrop() {
	document.onmousedown = OnMouseDown;
	document.onmouseup = OnMouseUp;
}

function classDrag(e, target) {

		// grab the mouse position
		_startX = e.clientX;
		_startY = e.clientY;

		// grab the clicked element's position
		_offsetX = ExtractNumber(target.style.left);
		_offsetY = ExtractNumber(target.style.top);

		// bring the clicked element to the front while it is being dragged
		_oldZIndex = target.style.zIndex;
		target.style.zIndex = 10000;

		// we need to access the element in OnMouseMove
		_dragElement = target;

		// tell our code to start moving the element with the mouse
		document.onmousemove = OnMouseMove;

		// cancel out any text selections
		document.body.focus();

		// prevent text selection in IE
		document.onselectstart = function () { return false; };

		// prevent IE from trying to drag an image
		target.ondragstart = function() { return false; };

		// prevent text selection (except IE)
		return false;

}

function strapPos(dragE) {

	dragE.style.display = 'block';
}

function classStrap( e, target ) {

		dragE = document.getElementById('move_strap');
		dragE.src = target.src.replace('/thumb', '');

		_scrollY = 0;
		if ( document.documentElement ) {
			_scrollY = document.documentElement.scrollTop;
		} else {
			_scrollY = window.pageYOffset;
		}

		// grab the mouse position
		_startX = dragE.width/2;
		_startY = (dragE.height/2)-_scrollY;

		// grab the clicked element's position
		_offsetX = ExtractNumber(target.style.left);
		_offsetY = ExtractNumber(target.style.top);

		// bring the clicked element to the front while it is being dragged
		_oldZIndex = target.style.zIndex;


		// we need to access the element in OnMouseMove
/*
		dragE.style.position = 'absolute';
		dragE.style.left = e.clientX-_startX+'px';
		dragE.style.top = e.clientY-_startY+'px';
		dragE.style.zIndex = 10000;
*/
		_dragElement = dragE;

		// tell our code to start moving the element with the mouse
		document.onmousemove = OnMouseMove;

		// cancel out any text selections
		document.body.focus();

		// prevent text selection in IE
		document.onselectstart = function () { return false; };

		// prevent IE from trying to drag an image
		target.ondragstart = function() { return false; };

//		dragE.style.display = 'block';

		// prevent text selection (except IE)
		return false;
}

function OnMouseDown(e) {
	// IE is retarded and doesn't pass the event object
	if (e == null) e = window.event;

	// IE uses srcElement, others use target
	var target = e.target != null ? e.target : e.srcElement;
//	_debug.innerHTML = target.className == 'drag' ? 'draggable element clicked' : 'NON-draggable element clicked';

	// for IE, left click == 1
	// for Firefox, left click == 0
	if ((e.button == 1 && window.event != null || e.button == 0) ) {
		if ( target.className == 'drag' ) {
			return classDrag(e, target);
		} else
		if ( target.className == 'strap' ) {
			return classStrap(e, target);
		}
	}
}


function OnMouseMove(e) {

	if (e == null) var e = window.event;

	// this is the actual "drag code"
	_dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
	_dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';
//	_debug.innerHTML = '(' + _dragElement.style.left + ', ' + _dragElement.style.top + ')';

}

function OnMouseUp(e) {
	if (_dragElement != null) {

       	createCookie('cartPost',_dragElement.style.left+' '+_dragElement.style.top,0);

		_dragElement.style.zIndex = _oldZIndex;

		// we're done with these events until the next OnMouseDown
		document.onmousemove = null;
		document.onselectstart = null;
		_dragElement.ondragstart = null;

		// this is how we know we're not dragging
		if ( _dragElement.className == 'strap' ) {
			_dragElement.style.display = 'none';
		}

		_dragElement = null;
//		_debug.innerHTML = 'mouse up';
	}
}

function ExtractNumber(value) {
	var n = parseInt(value);
	return n == null || isNaN(n) ? 0 : n;
}