// JavaScript Document

var clipID;
var clipLink = 1;
var categoryID = 1;
var articleID = 0;

function Pokaz(div) {
	
	if (document.filters.clicker.value=='Close filter dialog') {
	
		Effect.BlindUp(div); 
		document.filters.clicker.value='Open filter dialog';
	
	} else {
		Effect.BlindDown(div); 
		document.filters.clicker.value='Close filter dialog';
	}
	
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

        function okno(url,opcje,id) {
            window.open(url,id,opcje,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes');
        }

	function encodeString(text) {
		encoded = text.replace("///g","%2F");
		encoded = encoded.replace("/?/g","%3F");
		encoded = encoded.replace("/=/g","%3D");
		encoded = encoded.replace("/&/g","%26");
		encoded = encoded.replace("/#/g","%23");
		encoded = encoded.replace("/@/g","%40");
		encoded = encoded.replace("/r/g","");
		encoded = encoded.replace("/n/g","%0A");
		return encoded;
	}

	function sendForm() {

		var id = document.formskr.looking.options.selectedIndex;
		var looking = document.formskr.looking.options[id].value; 					
		id = document.formskr.trades.options.selectedIndex;
		var trades = document.formskr.trades.options[id].value;
					
		var town = document.formskr.town.value;
		var post = document.formskr.post.value;
		var name = document.formskr.name.value;
		var tel = document.formskr.tel.value;
		var desc = document.formskr.desc.value;
		var email = document.formskr.email.value;

		desc = encodeString(desc);		
		var message = "";
		var cat = "";
		
		var regEmail = /^.+\@.+\..+$/;


                if (looking == "-----Select Closest Match-----") message = message + "Fill the field: What are you looking for!\n";
		
                if (trades == "-----Select Closest Match-----") message = message + "Fill the fields: TRADES!\n"; else cat = trades;
                    
                    
                if (town.length == 0) message = message + "Fill the field: CITY!\n";
                if (post.length == 0) message = message + "Fill the field: POST OF JOB!\n";
                if (desc.length == 0) message = message + "Fill the field: DESCRIPTION!\n";
                if (email.length == 0) message = message + "Fill the field: E-MAIL!\n"; else {
                    if (!regEmail.test (email)) message = message + "Incorrect: E-MAIL!\n";
                };
                
	if ( message.length > 0 )
	{
		alert( message );
		return false;
	}
	else
	{
            okno('http://www.telehandyman.co.uk/add.php?looking=' + looking + '&trades=' + trades + '&town=' + town + '&post=' + post + '&name=' + name + '&tel=' + tel + '&email=' + email + '&desc=' + desc,'height=120,width=200');
	    return false;
	}
	
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function showCategory ( id )
{
	var menuItems = getElementsByClassName ( "articleCategory", "a" );
	var menuIdx = 0;
	articleID = 0;
	categoryID = id;
	for ( var i = 0; i < menuItems.length; i++ )
	{
		if ( menuItems[i].id == "articleCategory_" + id )
			menuIdx = i;
		
		menuItems[i].className = "articleCategory";
	}
	document.getElementById ( "articleCategory_" + id ).className = "articleCategory selected";
	
	var articleLists = getElementsByClassName ( "articleList", "div" );
	for ( var i = 0; i < articleLists.length; i++ )
	{
		articleLists[i].className = "articleList closed";
	}
	$("articleList_" + id).className = "articleList open";
	
	$('catArrow').setStyle ( "top", ( 4 + ( 37 * menuIdx ) + "px" ) );
	$('catArrow').getFirst().href = "http://closeup.mogio.co.uk/videos/" + $("articleCategory_" + id).innerHTML.replace(/ /, "_");
	$('allArticles').href= "http://closeup.mogio.co.uk/videos/" + $("articleCategory_" + id).innerHTML.replace(/ /, "_");
}

function previousArticle ()
{
	if ( articleID == 0 ) return;
	var articleLists = $$('#articleList_' + categoryID + ' .articleItem');
	articleLists[articleID].removeClass ( "open" );
	articleLists[articleID].addClass ( "closed" );
	articleLists[--articleID].removeClass ( "closed" );
	articleLists[articleID].addClass ( "open" );
}

function nextArticle ()
{
	var articleLists = $$('#articleList_' + categoryID + ' .articleItem');
	if ( articleID + 2 > articleLists.length ) return;
	articleLists[articleID].removeClass ( "open" );
	articleLists[articleID].addClass ( "closed" );
	articleLists[++articleID].removeClass ( "closed" );
	articleLists[articleID].addClass ( "open" );
}

// 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 + "=" + encodeURIComponent ( args[key] ) );
		args = argArr.join ( "&" );
	}
	request.send(args);
}

// Admin
	
ajaxRequest ( "remote.php?action=check_login", {}, adminShowControls );

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;';
		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'>Notice</div>";
		else if ( windowType == 'warning' )
			contentDiv.innerHTML = "<div id='mbox_header'>Warning</div>";
		else if ( windowType == 'error' )
			contentDiv.innerHTML = "<div id='mbox_header'>Error!</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'>Password:</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 ( "remote.php?action=login", { login: $('admin_login').value, password: $('admin_password').value }, adminLoginDoCheck );
	toggleMBox ( false );
}

function adminLoginDoCheck ( response )
{
	if ( response == "error" )
		toggleMBox ( "error", "Login or/and password you provided are incorrect!", [ [ "Ok", function () { toggleMBox () } ] ] );
	else if ( response == "ok" )
	{
		toggleMBox ( "info", "You are now logged in!", [ [ "Ok", function () { toggleMBox () } ] ] );
		adminShowControls ( response );
	}
	else
		toggleShade ();
}

function adminShowControls ( response )
{
	if ( response != "ok" ) return false;
	$$(".clip").forEach ( function ( div ) {
		var id = div.id;
		var editLink = new Element ( "A", {
			"html": "[ Edit this area ]",
			"href": "javascript:void(0);",
			"events": {
				"click": function () {
					clipID = id;
					ajaxRequest ( "remote.php?action=get_clip", { clip: clipID, link: clipLink }, adminEditClipPrepare );
				}
			}
		} );
		editLink.injectAfter ( div );
		if ( id == "closeup-right" )
		{
			var addLink = new Element ( "A", {
				"html": "[ Add clip ] ",
				"href": "javascript:void(0);",
				"events": {
					"click": function () {
						clipID = id;
						ajaxRequest ( "remote.php?action=add_clip", { clip: clipID }, adminAddClip );
					}
				}
			} );
			addLink.injectAfter ( div );
		}
	} );
}

function adminEditClipPrepare ( response )
{
	toggleShade ();
	toggleMBox ( "applet", "<textarea id='clip-edit' style='width: 300px; height: 180px;'></textarea>", [ [ "Cancel", function () { toggleMBox () } ], [ "Save", adminEditClip ] ], "Area edit box" );
	$('clip-edit').set ( "value", response );
}

function adminEditClip () {
	ajaxRequest ( "remote.php?action=edit_clip", { clip: clipID, link: clipLink, content: $('clip-edit').get("value") }, function ( response ) {
		if ( clipID == "closeup-left" )
			$(clipID).set ( "html", $('clip-edit').get("value") );
		else {
			$("closeup-right-" + clipLink).set ( "html", $('clip-edit').get("value") );
		}
		toggleMBox ();
	} );
}

function showClip ( id )
{
	clipLink = id;
	$$(".clip-part").setStyle ( "display", "none" );
	$("closeup-right-" + id).setStyle ( "display", "block" );
	$$(".closeup-right-link").removeClass ( "active-link" );
	$("closeup-right-link-" + id).addClass ( "active-link" );
}

function adminAddClip ( response ) {	
	var newLink = new Element ( "A", {
		"html": response,
		"href": "javascript:showClip(" + response + ");",
		"id": "closeup-right-link-" + response,
		"class": "closeup-right-link"
	} );
	newLink.inject ( "closeup-right-links", "top" );
	var newDiv = new Element ( "DIV", {
		"id": "closeup-right-" + response,
		"class": "clip-part",
		"html": "Clip content",
		"styles": {
			"display": "none"
		}
	} );
	newDiv.inject ( "closeup-right", "top" );
}

window.addEvent ( "domready", function () {
	showCategory ( 1 );
	// Search box
	
	if ( $('searchQuery').value == "" || $('searchQuery').value == "enter exact product name" )
	{
		$('searchQuery').value = "enter exact product name";
		$('searchQuery').setStyle ("color", "#aaa");
	}

	$('searchQuery').addEvent ( "focus", function () {
		if ( $('searchQuery').value == "enter exact product name" )
		{
			$('searchQuery').value = "";
			$('searchQuery').setStyle ("color", "#000");
		}
	} );
	
	$('searchQuery').addEvent ( "blur", function () {
		if ( $('searchQuery').value == "" )
		{
			$('searchQuery').setStyle ("color", "#aaa");
			$('searchQuery').value = "enter exact product name";
		}
	} );
} );
