var existingFilters = [];
var url;
url = top.location.href;

var query = this.location.href.substr ( url.length ).split ( "/" );

function getBase()
{
      var baseTag = document.getElementsByTagName("base");
      for(var i=0; i<baseTag.length; i++)
      {
            var baseId = baseTag[i].id;
            var baseHref = baseTag[i].href;
      }
	  return baseHref;
}

// AJAX FUNCTIONS

function ajaxInitObj() {
	try	{
		var x = new XMLHttpRequest();
	}
	catch (error) {
		try {
			var x = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (error) {
			try {
				var x = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (error) {
				return false;
			}
		}
	}
	return x;
}

function ajaxRequest(url, args, callback) {
	var request = ajaxInitObj();
	request.open('POST', url, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.setRequestHeader('Connection','close');
	request.onreadystatechange = function() {
		if (request.readyState != 4) 
			return;
		callback(request.responseText);
		if(!window.ActiveXObject) delete request;
		else request = null;
	}
	if ( $type (args) == 'object' )
	{
		var argArr = [];
		for (var key in args)
			argArr.push ( key + "=" + args[key].replace("&","%26") );
		args = argArr.join ( "&" );
	}
	request.send(args);
}

function isInt(x) {
	var y=parseInt(x);
	if (isNaN(y)) return false;
	return x==y && x.toString()==y.toString();
} 

function applyFilter ( obj ) {
	query = [""];
	var filterName = obj.name.substr ( obj.name.indexOf ( "_" ) + 1 );
	var exists = false;
	var croppedUrl = url;
	if ( existingFilters.length > 0 )//jezeli wczesniej byl ustawiony jakis filtr to nalezy uciac url
	{
		var lastSlash = url.lastIndexOf("/");
		croppedUrl = url.substring(0,lastSlash);
	}
	for ( var i = 0; i < existingFilters.length; i++ )
	{
		if ( existingFilters[i].indexOf ( filterName ) != -1 )
		{
			exists = true;
			if ( obj.options[obj.options.selectedIndex].value != "" )
				existingFilters[i] = filterName + ":" + obj.options[obj.options.selectedIndex].value;
			else
			{
				existingFilters.splice ( i, 1 );
			}
		}
	}
	if ( exists == false )
		existingFilters.push ( filterName + ":" + obj.options[obj.options.selectedIndex].value.replace ( /&/, "_amp_" ) );
	
	if ( isInt ( query[query.length-1] ) )
		query.pop ();
	
	if ( existingFilters.length > 0 )
		top.location.href = croppedUrl + "/" + existingFilters.join(",");
	else
		top.location.href = croppedUrl + "/1";
}

window.addEvent ( "domready", function () {
	query = this.location.href.split ( "/" ); 
	if ( query[query.length - 1].match ( /^\d$/ ) )
	{
		if ( query[query.length - 2].indexOf ( ":" ) != -1 )
		{
			existingFilters = query[query.length - 2].split ( "," );
			query.pop();
		}
		query.pop();
	}
	else
	{
		if ( query[query.length - 1].indexOf ( ":" ) != -1 )
		{
			existingFilters = query[query.length - 1].split ( "," );
			query.pop();
		}
	}
	for ( var i = 0; i < existingFilters.length; i++ )
	{
		var filter = existingFilters[i].split ( ":" );
		var sel = document.getElementById ( "filter_" + filter[0] );
		for ( j = 0; j < sel.options.length; j++ )
		{
			if ( sel.options[j].value == filter[1].replace ( /%20/g, " " ).replace ( /_amp_/, "&" ) )
				sel.options.selectedIndex = j;
		}
	}
	
	// Search box
	
	if ( $('searchQuery').value == "" || $('searchQuery').value == "podaj nazwę produktu" )
	{
		$('searchQuery').value = "podaj nazwę produktu";
		$('searchQuery').setStyle ("color", "#aaa");
	}

	$('searchQuery').addEvent ( "focus", function () {
		if ( $('searchQuery').value == "podaj nazwę produktu" )
		{
			$('searchQuery').value = "";
			$('searchQuery').setStyle ("color", "#000");
		}
	} );
	
	$('searchQuery').addEvent ( "blur", function () {
		if ( $('searchQuery').value == "" )
		{
			$('searchQuery').setStyle ("color", "#aaa");
			$('searchQuery').value = "podaj nazwę produktu";
		}
	} );
	
	// Admin
	
	ajaxRequest ( getBase()+"php/remote.php?action=check_login", {}, adminShowControls );
} );

function doSearch ()
{
//	if ( query[0] == "search" )
		top.location.href = url + "/search/" + $('searchQuery').value;
//	else
//		top.location.href = url + query[0] + "/search/" + $('searchQuery').value;
	return false;
}

function toggleShade ()
{
	if ( $( 'shade' ) == null )
	{
		var shade = document.createElement ( 'DIV' );
		shade.id = 'shade';
		if ( Browser.Engine.trident )
			shade.style.backgroundColor = '#000000';
		else
			shade.className = 'shade';
		shade.style.position = 'absolute';
		shade.style.top = '0px';
		shade.style.opacity = 0;
		shade.style.left = '0px';
		shade.style.height = Window.getScrollHeight() + 'px';
		shade.style.width = ( Window.getScrollWidth() - 1 ) + 'px';
		document.body.appendChild ( shade );
		if ( Browser.Engine.trident  )
			$(shade).tween ( "opacity", [0, 0.2] );
		else
			$(shade).tween ( "opacity", [0, 1] );
		shade.style.zIndex = '100';
	}
	else
	{
		document.body.removeChild ( $( 'shade' ) );
	}
	
}

function toggleMBox ( windowType, content, buttons, customHeader, customWidth )
{
	if ( windowType != null && $ ( 'mbox' ) != null )
		document.body.removeChild ( $ ( 'mbox' ) );
	if ( windowType != false )
	if ( $ ( 'mbox' ) == null )
	{
		var mbox = document.createElement ( 'DIV' );
		mbox.id = 'mbox';
		//mbox.style.width = '300px;';
		$(mbox).setStyle('width', '300px');
		//if ( windowType == "applet" )
		//	if ( customWidth != undefined )
		//		mbox.style.width = customWidth + 'px;';
		//	else
		//		mbox.style.width = '350px;';
		//mbox.style.zIndex = '1000';
		//mbox.style.position = 'absolute';
		//mbox.style.visibility = 'hidden';
		document.body.appendChild ( mbox );
		var contentDiv = document.createElement ( 'DIV' );
		contentDiv.style.position = 'relative';
		if ( windowType == 'info' )
			contentDiv.innerHTML = "<div id='mbox_header'>Gratulacje!</div>";
		else if ( windowType == 'warning' )
			contentDiv.innerHTML = "<div id='mbox_header'>Ostrzeżenie!</div>";
		else if ( windowType == 'error' )
			contentDiv.innerHTML = "<div id='mbox_header'>Błąd!</div>";
		else if ( customHeader != null )
			contentDiv.innerHTML = "<div id='mbox_header'>" + customHeader + "</div>";
		contentDiv.innerHTML += "<div id='mbox_content'>" + content + "</div>";
		mbox.appendChild ( contentDiv );
		if ( buttons && buttons.length > 0 )
		{
			var buttonDiv = document.createElement ( 'DIV' );
			buttonDiv.id = 'mbox_buttons';
			for ( var i = 0; i < buttons.length; i++ )
			{
				var button = document.createElement ( 'INPUT' );
				button.className = 'mbox_button';
				button.type = 'button';
				button.value = buttons[i][0];
				button.onclick = buttons[i][1];
				if ( buttons[i][2] )
					button.setAttribute ( 'style', buttons[i][2] );
				buttonDiv.appendChild ( button );
			}
			contentDiv.appendChild ( buttonDiv );
		}
		mbox.style.left = ( ( Window.getWidth() / 2 ) - ( $(mbox).getSize().x / 2 ) ) + 'px';
		mbox.style.top = ( Window.getHeight() / 2 ) - ( $(mbox).getSize().y / 2 ) + Window.getScrollTop() + 'px';
		$(mbox).tween ( "opacity", [0, 1] );
	}
	else
	{
		$("mbox").tween ( "opacity", [1, 0] );
		if ( windowType == null )
			window.setTimeout ( "toggleShade ();", 300 );
	}
}

// ADMIN

function adminLogin () {
	toggleShade ();
	toggleMBox ( "applet", "<div class='window_form'><div class='window_form_left'>Login:</div><div class='window_form_right'><input type='text' id='admin_login' name='admin_login' /></div><br /><div class='window_form_left'>Hasło:</div><div class='window_form_right'><input type='password' id='admin_password' name='admin_password' /></div><br /></div>", [ [ "Anuluj", function () { toggleMBox () } ], [ "Zaloguj", adminLoginDo ] ], "Logowanie" );
}

function adminLoginDo () {
	ajaxRequest ( getBase()+"php/remote.php?action=login", { login: $('admin_login').value, password: $('admin_password').value }, adminLoginDoCheck );
	toggleMBox ( false );
}

function adminLoginDoCheck ( response )
{
	if ( response == "error" )
		toggleMBox ( "error", "Login lub/i hasło jest nieprawidłowe!", [ [ "Ok", function () { toggleMBox () } ] ] );
	else if ( response == "ok" )
		toggleMBox ( "info", "Jesteś zalogowany!", [ [ "Ok", function () { toggleMBox (); top.location.href = top.location.href } ] ] );
	else
		toggleShade ();
}

function adminShowControls ( response )
{
	if ( response != "ok" ) return false;
	else
	{
	//document.getElement("#rightSide > table > thead > tr").getLast().set ( "html", "Opcje" );
	$$(".ProdBasket").forEach ( function ( row, idx ) {
		row.set ( "html", "" );
		var btnPromoCode = new Element ( "img", {
			"class": "admin_button",
			"src": getBase()+"image/promo_code.png",
			"events": {
				"click": function () {
					adminPromoCode ( this )
				}
			}
		} );
		var btnPromoCodeAll = new Element ( "img", {
			"class": "admin_button",
			"src": getBase()+"image/promo_code_all.png",
			"events": {
				"click": function () {
					adminPromoCodeAll ( this )
				}
			}
		} );
		var btnPriceEdit = new Element ( "img", {
			"class": "admin_button",
			"src": getBase()+"image/price_edit.png",
			"events": {
				"click": function () {
					adminEditProductPrice ( this )
				}
			}
		} );
		var btnPricePromo = new Element ( "img", {
			"class": "admin_button",
			"src": getBase()+"image/price_promo.png",
			"events": {
				"click": function () {
					adminEditProductPromoPrice ( this )
				}
			}
		} );
		var btnEdit = new Element ( "img", {
			"class": "admin_button",
			"src": getBase()+"image/tag_blue_edit.png",
			"events": {
				"click": function () {
					adminEditProduct ( this )
				}
			}
		} );
		var btnDelete = new Element ( "img", {
			"class": "admin_button",
			"src": getBase()+"image/tag_blue_delete.png",
			"events": {
				"click": function () {
					adminDeleteProduct ( this )
				}
			}
		} );
		btnPriceEdit.injectInside ( row );
		btnPricePromo.injectInside ( row );
		btnEdit.injectInside ( row );
		btnDelete.injectInside ( row );
		btnPromoCode.injectInside ( row );
		btnPromoCodeAll.injectInside ( row );
	} );
}
	
	if ( response != "ok" ) return false;
	else
	{
	$$(".clip").forEach ( function ( div ) {
		var id = div.id;
		var editLink = new Element ( "A", {
			"html": "[ Edytuj ten obszar ]",
			"href": "javascript:void(0);",
			"events": {
				"click": function () {
					ajaxRequest ( getBase()+"php/remote.php?action=get_clip", { clip: "nad_tabelka" }, adminEditClipPrepare );
				}
			}
		} );
		editLink.injectAfter ( div );
	} );
	
	$$(".clip2").forEach ( function ( div ) {
		var id = div.id;
		var editLink = new Element ( "A", {
			"html": "[ Edytuj ten obszar ]",
			"href": "javascript:void(0);",
			"events": {
				"click": function () {
					ajaxRequest ( getBase()+"php/remote.php?action=get_clip", { clip: "nad_bannerem" }, adminEditClipPrepare2 );
				}
			}
		} );
		editLink.injectAfter ( div );
	} );
	}
	
}

function adminEditProduct ( obj )
{
	var productNameTD = obj.getParent().getParent().getFirst().getNext();
	var url = productNameTD.getFirst().href;
	var productName = obj.getParent().getParent().getFirst().getNext().getFirst().get ( "html" );
	var productID = url.substr ( url.lastIndexOf ( "/" ) + 1, url.indexOf ( "_", url.lastIndexOf ( "/" ) ) - url.lastIndexOf ( "/" ) - 1 );
	productNameTD.set ( "html", "" );
	var txtName = new Element ( "input", {
		"rel": productID,
		"value": productName,
		"events": {
			"keyup": function ( e ) {
				if ( e.key == "enter" )
				{
					productNameTD.getFirst().disabled = true;
					ajaxRequest ( getBase()+"php/remote.php?action=product_edit", { id: productID, name: productNameTD.getFirst().value }, function () {
						productNameTD.set ( "html", "<a href='" + url + "'>" + productNameTD.getFirst().value + "</a>" );
					} );
				}
			}
		}
	} );
	txtName.injectInside ( productNameTD );
}

function adminEditProductPrice ( obj )
{
	var productPriceTD = obj.getParent().getParent().getFirst().getNext().getNext().getNext().getElement ( ".price" );
	var url = obj.getParent().getParent().getFirst().getNext().getFirst().href;
	if ( $type ( productPriceTD.getFirst() ) != false )
		productPriceTD = productPriceTD.getFirst();
	
	var productPrice = productPriceTD.get ( "html" );
	if ( productPrice == "Contact merchant" )
		productPrice = 0;
	else
		if ( productPriceTD.get("html").indexOf ( "was" ) == -1 )
			productPrice = productPrice.substring ( 1 );
		else
			productPrice = productPrice.substring ( 5 );			
		
	var productID = url.substr ( url.lastIndexOf ( "/" ) + 1, url.indexOf ( "_", url.lastIndexOf ( "/" ) ) - url.lastIndexOf ( "/" ) - 1 );
	productPriceTD.set ( "html", "" );
	var txtPrice = new Element ( "input", {
		"rel": productID,
		"value": productPrice,
		"styles": {
			width: "60px"
		},
		"events": {
			"keyup": function ( e ) {
				if ( e.key == "enter" )
				{
					productPriceTD.getFirst().disabled = true;
					ajaxRequest ( getBase()+"php/remote.php?action=product_price_edit", { id: productID, price: productPriceTD.getFirst().value }, function () {
						if ( productPriceTD.hasClass ( "price_was" ) == false )
							productPriceTD.set ( "html", "" + productPriceTD.getFirst().value );
						else
							productPriceTD.set ( "html", "było" + productPriceTD.getFirst().value );
					} );
				}
			}
		}
	} );
	txtPrice.injectInside ( productPriceTD );
}

function adminEditProductPromoPrice ( obj )
{
	var productPriceTD = obj.getParent().getParent().getFirst().getNext().getNext().getNext().getElement ( ".price" );
	var url = obj.getParent().getParent().getFirst().getNext().getFirst().href;
	if ( $type ( productPriceTD.getFirst() ) != false )
		productPriceTD = productPriceTD.getFirst().getNext();

	var productPrice = productPriceTD.get ( "html" );
	if ( productPrice == "Contact merchant" )
	{
		alert ( "Ustaw najpierw cenę dla tego produktu!" );
		return;
	}

	if ( productPriceTD.get("html").indexOf ( "now" ) == -1 )
		productPrice = productPrice.substring ( 1 );
	else
		productPrice = productPrice.substring ( 5 );			
		
	var productID = url.substr ( url.lastIndexOf ( "/" ) + 1, url.indexOf ( "_", url.lastIndexOf ( "/" ) ) - url.lastIndexOf ( "/" ) - 1 );
	productPriceTD.set ( "html", "" );
	var txtPrice = new Element ( "input", {
		"rel": productID,
		"value": productPrice,
		"styles": {
			width: "60px"
		},
		"events": {
			"keyup": function ( e ) {
				if ( e.key == "enter" )
				{
					productPriceTD.getFirst().disabled = true;
					ajaxRequest ( getBase()+"php/remote.php?action=product_price_promo", { id: productID, price: productPriceTD.getFirst().value }, function () {
						if ( productPriceTD.getFirst().value != 0 )
						{
							if ( productPriceTD.getPrevious().get("html").indexOf ( "was" ) == -1 )
								productPriceTD.set ( "html", "<div class='price_was'>was &pound;" + productPrice + "</div><div class='price_now'>now &pound; " + productPriceTD.getFirst().value + "</div>" );
							else
								productPriceTD.set ( "html", "now &pound;" + productPriceTD.getFirst().value );
						}
						else
							if ( productPriceTD.getPrevious().get("html").indexOf ( "was" ) == -1 )
								productPriceTD.set ( "html", "&pound;" + productPriceTD.getPrevious().get("html").substring ( 2 ) );
							else
								productPriceTD.getParent().set ( "html", "&pound;" + productPriceTD.getPrevious().get("html").substring ( 6 ) );
					} );
				}
			}
		}
	} );
	txtPrice.injectInside ( productPriceTD );
}

function adminDeleteProduct ( obj )
{
	var productNameTD = obj.getParent().getParent().getFirst().getNext();
	var url = productNameTD.getFirst().href;
	var productID = url.substr ( url.lastIndexOf ( "/" ) + 1, url.indexOf ( "_", url.lastIndexOf ( "/" ) ) - url.lastIndexOf ( "/" ) - 1 );
	toggleShade ();
	toggleMBox ( "warning", "Czy na pewno chcesz usunąć produkt '" + productNameTD.getFirst().get("html") + "'?", [ [ "Nie", function () { toggleMBox () } ], [ "Tak", function () {
		ajaxRequest ( getBase()+"php/remote.php?action=product_delete", { id: productID }, function () {
			productNameTD.getParent().fade( "out" );
			top.location.href = location.href;
		} );
	} ] ], "Usuwanie produktu" );	
}

function adminPromoCode ( obj )
{
	var productVoucher = obj.getParent().getParent().getFirst().getNext().getNext().getNext().getElement ( "img.voucher" );
	var voucher = "";
	if ( productVoucher != null )
		voucher = productVoucher.get ( "alt" );
		
	toggleShade ();
	toggleMBox ( "applet", "<div class='window_form'>Wpisz kod promocyjny<br /><br /><div class='window_form_left'>Promo code info:</div><div class='window_form_right'><textarea id='promo_code' name='promo_code'>" + voucher + "</textarea></div><br /></div>", [ [ "Anuluj", function () { toggleMBox () } ], [ "Zapisz", function () {
		var productNameTD = obj.getParent().getParent().getFirst().getNext();
		var url = productNameTD.getFirst().href;
		var productName = obj.getParent().getParent().getFirst().getNext().getFirst().get ( "html" );
		var productID = url.substr ( url.lastIndexOf ( "/" ) + 1, url.indexOf ( "_", url.lastIndexOf ( "/" ) ) - url.lastIndexOf ( "/" ) - 1 );
		ajaxRequest ( getBase()+"php/remote.php?action=promo_code_edit", { id: productID, promo_code: $('promo_code').value }, function ( response ) {
			toggleMBox ( "info", "Kod promocyjny dodany!", [ [ "Ok", function () { toggleMBox (); top.location.href = top.location.href } ] ] );
		} );
		toggleMBox ( false );
	} ] ], "Promo code information" );
}

function adminPromoCodeAll ( obj )
{
	var productVoucher = obj.getParent().getParent().getFirst().getNext().getNext().getNext().getElement ( "img.voucher" );
	var voucher = "";
	if ( productVoucher != null )
	{
		voucher = productVoucher.get ( "alt" );
	}

	toggleShade ();
	toggleMBox ( "applet", "<div class='window_form'>Zatwierdź kod promocyjny dla wszystkich produktów<br /><br /><div class='window_form_left'>Promo code info:</div><div class='window_form_right'><textarea id='promo_code' name='promo_code'>" + voucher + "</textarea></div><br /></div>", [ [ "Cancel", function () { toggleMBox () } ], [ "Apply", function () {
		var productNameTD = obj.getParent().getParent().getFirst().getNext();
		var url = productNameTD.getFirst().href;
		var productName = obj.getParent().getParent().getFirst().getNext().getFirst().get ( "html" );
		var productID = url.substr ( url.lastIndexOf ( "/" ) + 1, url.indexOf ( "_", url.lastIndexOf ( "/" ) ) - url.lastIndexOf ( "/" ) - 1 );
		ajaxRequest ( getBase()+"php/remote.php?action=promo_code_all_edit", { id: productID, promo_code: $('promo_code').value }, function ( response ) {
			toggleMBox ( "info", "Kod promocyjny dodany!" + response, [ [ "Ok", function () { toggleMBox (); top.location.href = top.location.href } ] ] );
		} );
		toggleMBox ( false );
	} ] ], "Add promo code for merchant" );	
}




function adminEditClipPrepare ( response )
{
	toggleShade ();
	toggleMBox ( "applet", "<textarea id='clip-edit' style='width: 300px; height: 180px;'></textarea>", [ [ "Anuluj", function () { toggleMBox () } ], [ "Zapisz", adminEditClip ] ], "Okienko edycji obszaru" );
	$('clip-edit').set ( "value", response );
}
function adminEditClipPrepare2 ( response )
{
	toggleShade ();
	toggleMBox ( "applet", "<textarea id='clip-edit' style='width: 300px; height: 180px;'></textarea>", [ [ "Anuluj", function () { toggleMBox () } ], [ "Zapisz", adminEditClip2 ] ], "Okienko edycji obszaru" );
	$('clip-edit').set ( "value", response );
}

function adminEditClip () {
	ajaxRequest ( getBase()+"php/remote.php?action=edit_clip", { clip: "nad_tabelka", content: $('clip-edit').get("value") }, function ( response ) {
		$('rc_discounts').set ( "html", $('clip-edit').get("value") );
		toggleMBox ();
	} );
}
function adminEditClip2 () {
	ajaxRequest ( getBase()+"php/remote.php?action=edit_clip", { clip: "nad_bannerem", content: $('clip-edit').get("value") }, function ( response ) {
		$("nad_banerem").set ( "html", $('clip-edit').get("value") );
		toggleMBox ();
	} );
}
