// $IDG: zoom_album/themes/default/javascript/default.js,v 1.8 2005/12/27 13:47:40 svdgraaf Exp $

var req = '';
var currentIntervalId = '';
var redirectUrl = '';
var rotateId = '';

String.prototype.isEmail    = function () {    var emailregex = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/; return emailregex.test(this);}
String.prototype.trim       = function(){return this.replace(/^\s+|\s+$/g,"");};


function doCheckCommentLength(min_comment_length)
{
	var commentField = $('commentField');

	var char_count = commentField.value.length;
	var fullStr = commentField.value + " ";
	var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
	var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
	var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
	var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
	var splitString = cleanedStr.split(" ");
	var word_count = splitString.length -1;

	$('commentFieldLength').innerHTML = word_count;

	if(word_count > 0)
	{
		$('commentLengthDescription').style.display = 'none';
		$('commentLengthCounter').style.display = 'block';
	}
	else
	{
		$('commentLengthDescription').style.display = 'block';
		$('commentLengthCounter').style.display = 'none';
	}

	if(word_count >= min_comment_length)
	{
		$('commentSubmit').disabled = false;
		$('commentFieldLength').style.color = 'green';
	}
	else
	{
		$('commentSubmit').disabled = true;
		$('commentFieldLength').style.color = 'red';
	}
}

function toggleDiv(divObject, type)
{
	if(typeof(document.getElementById('')) == 'object')
	{
		if(obj_div = document.getElementById(divObject))
		{

			if(type != null && type == true)
			{
				obj_div.style.display = 'block';
			}

			if(type != null && type == false)
			{
				obj_div.style.display = 'none';
			}

			if(type == null)
			{
				// toggle the div's
				if(obj_div.style.display == 'none')
				{
					// not just yet
					// setToggleCookie(divObject,'true',true);
					obj_div.style.display = 'block';
				}
				else
				{
					//not just yet
					//setToggleCookie(divObject,'false',true);
					obj_div.style.display = 'none'
				}
			}

			// check for breakout / breakin images
			if(obj_img = document.getElementById(divObject + 'Img'))
			{
				if(obj_div.style.display == 'none')
				{
					obj_img.src = '/img/plus.gif';
				}
				else
				{
					obj_img.src = '/img/min.gif';
				}
			}
		}
		else
		{
			alert('div ' + divObject + ' not found');
			return false;
		}

		return true;
	}
	else
	{
		// no DOM, get a real browser!
		alert('no DOM found, get a real browser!');
	}
}

function setImagesPerPage(amount)
{
	setCookie('images_per_page', amount, false ,'/');
	document.location.reload(1);
}

function printNewTag()
{
    if(req.readyState == 4 && req.status == 200)
    {
	if(req.responseText != '')
	{
		document.getElementById('tagList').innerHTML = document.getElementById('tagList').innerHTML + req.responseText;
	}
	else
	{
		alert('De tag is niet toegevoegd, waarschijnlijk is deze al toegevoegd');
	}
    }
}

function addTag(tag, imageId, callFunction)
{
    var tag = tag.replace(/^\s+/, '');
    tag = tag.replace(/\s+$/, '');
//    tag = tag.replace(/[^a-zA-Z0-9]/g, '-');
    tag = tag.toLowerCase();
    tag = tag.substr(0, 32);
    var url = '/videos_tag/addTag/' + imageId + '/' + tag;

    loadXMLDoc(url, 'GET', false, printNewTag);
}

function loadXMLDoc(url, type, postData, callFunction)
{
	if(type == null)
	{
		type = 'GET';
	}

	req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest)
    {
    	try
    	{
        	req = new XMLHttpRequest();
        }
        catch(e)
        {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject)
    {
    	try
    	{
                req = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
        	try
        	{
            	req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
            	req = false;
            }
		}
    }
    if(req)
    {
        req.open(type, url, true);
        if(type == 'POST')
        {
        		// we need to set a header, otherwise, the post data won't be published
        		// by apache
        		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        		req.send(postData);
        }
        else
        {
            if(callFunction)
            {
                req.onreadystatechange = callFunction;
            }

            req.send('');
      	}
    }
}

function checkReqChange()
{
	if(req)
	{
		while(req.readyState != 4)
		{
			// wait till eternity...
		}
		return req.responseText;
	}
}

function nl2br(text)
{
	text = new String(text);
	rExp = /\n/gi;
	text = text.replace(rExp, '<br />');
	return text;
}

function nl20A(text)
{
	text = new String(text);
	rExp = /\n/gi;
	text = text.replace(rExp, '#nl#');
	return text;
}

function checkForReadyReqRedirect()
{
	if(req != '')
	{
		if(req.readyState >= 2 && redirectUrl != '')
		{
			document.location.href = redirectUrl;

			if(currentIntervalId != null)
			{
				clearInterval(currentIntervalId);
			}
		}
	}
}


function deleteTag(imageId, tagCounter, tagId)
{
	url = '/videos_tag/removeTag/' + imageId + '/' + tagId + '';
    loadXMLDoc(url);
	new Effect.Fade(tagCounter);
    //document.getElementById(tagCounter).style.display = 'none';
}

selectedFile = '';

function startPreview()
{
	previewChecker = window.setInterval('checkPreview()',10);
}

function checkPreview()
{
	if ($('file').value != '' && $('file').value != $('previewImage').value)
	{
		doPreview();
		window.clearInterval(previewChecker);
	}
}

function doPreview()
{
	// fetch the image filename
	str_imageFile = $('file').value;

	// we only do a new preview if the image is not empty, otherwise
	// we display the empty preview window
	if (str_imageFile != '')
	{
		$('previewEmpty').style.display = 'none';
		$('previewFilled').style.display = 'block';
		$('previewImage').src = 'file://' + str_imageFile;
		$('previewImage').style.width = '150';
	}
	else
	{
		$('previewEmpty').style.display = 'block';
		$('previewFilled').style.display = 'none';
	}
}

function deleteComment(commentId)
{
	if(confirm('Weet je zeker dat je dit commentaar wilt verwijderen?'))
	{
		url = '/comment/delete/' + commentId;
	    loadXMLDoc(url);
	    Effect.Fade('comment_' + commentId);
	}

	return false;
}

function deleteAlbum(albumId)
{
	if(confirm('Weet je zeker dat je dit album wilt verwijderen?'))
	{
		url = '/album/delete/' + albumId;
	    loadXMLDoc(url);
	    Effect.Fade('album_' + albumId);
	}

	return false;
}

function formChecker()
{
	var array_forms = document.getElementsByTagName('form');

	for(i=0;i<array_forms.length;i++)
	{
		array_forms[i].onsubmit = function(){
			var me = this;

			formError = false;

			for(i=0,j=me.elements.length;i<j;i++)
			{
				// is required?
				if(me.elements[i].className.indexOf('required') != -1)
				{
					if($F(me.elements[i]) == false)
					{
						$(me.elements[i]).style.border = '1px solid red';
						formError = true;
					}
				}

				// is email?
//				if(me.elements[i].className.indexOf('required') != -1)
//				{
//					if()
//
//				}
			}

			if(formError == true)
			{
				alert('Het formulier is niet volledig ingevuld, controleer de met de rood gemarkeerde velden.');
				return false;
			}
			else
			{
				return true;
			}

			// not reached
			return true;
		}
	}
}

function toggleMoreOrLess(self,target)
{
    $(self).style.display     =   'none';
    $(target).style.display =   'inline';
    return false;
}



function mailafriend(f)
{
    // validate
    var name    =   $F('from_name');
    var email   =   $F('to_email');

    if(name.trim().length == 0)
    {
        alert('vul je naam in');
        $('from_name').focus();
        return false;
    }
    if(!email.isEmail())
    {
        alert('vul je email in');
        $('to_email').focus();
        return false;
    }
    var videoid =   $F('mafvideoid');
    var url     =   $('mafform').getAttribute('action');

    var options     =   {asynchronous:'true',method:'post',postBody:Form.serialize(f),onComplete: function()
        {
        }};
    new Ajax.Updater('mafreport',url,options);

    $('to_email').value =   '';
    Effect.Fade('mafsubmitwrapper');

    setTimeout(function(){
        $('mafreport').innerHTML   =   '';
        Effect.Appear('mafsubmitwrapper');
        mailafriend_is_submitting   =   false;
    },4000);

    return false;
}

// image replacer
function firdom()
{
    if(document.getElementsByTagName && document.createElement)
    {
        for (l=1;l<=6;l++)
        {
            tagObjects = document.getElementsByTagName('h2');
            scanandreplace(tagObjects,'h2');
        }
    }
}

function scanandreplace(tagObjects, tag)
{
    for(i=0;i<tagObjects.length;i++)
    {
        obj_headerImage = document.createElement('img');
        if(tagObjects[i].firstChild.nodeValue != null)
        {
            obj_headerImage.src = '/header/' + tagObjects[i].firstChild.nodeValue
            oldStuff = tagObjects[i].replaceChild(obj_headerImage, tagObjects[i].firstChild);
        }
    }
}

function checkLoad()
{
    loadXMLDoc('/status/', 'GET', false, setLoad);
}

function setLoad()
{
    if(req.readyState == 4 && req.status == 200)
    {
        loadValue = parseFloat(req.responseText);
        if(loadValue > 5.0 && loadValue < 13.0)
        {
            Effect.Appear('loadDivIntermediate');
            $('loadImgIntermediate').title = "load: " + loadValue;
        }

        if(loadValue > 13.0)
        {
            Effect.Appear('loadDivHigh');
            $('loadImgHigh').title = "load: " + loadValue;
        }

//        if(loadValue < 1)
//        {
//            Effect.Appear('loadDivLow');
//        }
    }
}

Effect.ReSize = Class.create();
Object.extend(Object.extend(Effect.ReSize.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = element;
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ amount: 100, direction: 'vert', toSize:null }, arguments[1] || {});
    if( options.direction == 'vert' )
      this.originalSize = options.originalSize || parseInt(this.element.style.height);
    else
      this.originalSize = options.originalSize || parseInt(this.element.style.width);

    if( options.toSize != null )
      options.amount = options.toSize - this.originalSize;

    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if(this.element.getStyle('display')=='none') { this.cancel(); return; }
  },
  update: function(position) {
    if( this.options.direction == 'vert' ){
      this.element.setStyle({height: this.originalSize+(this.options.amount*position)+'px'});
    } else {
      this.element.setStyle({width: this.originalSize+(this.options.amount*position)+'px'});
    }
  },
  finish: function(){
    if( this.options.direction == 'vert' ){
      this.element.setStyle({height: this.originalSize+this.options.amount+'px'});
    } else {
      this.element.setStyle({width: this.originalSize+this.options.amount+'px'});
    }
  }
});

function loadComments(currentPage, itemsPerPage)
{
    var params = '';
    if(currentPage)
    {
        params = currentPage;
        if(itemsPerPage)
        {
            params += "/" + itemsPerPage;
        }
    }
    url = '/' + objectType + '/' + objectId + '/comments/' + params;
    new Ajax.Updater('imageComments', url, { method: 'get', evalScripts: true });

}

function saveComment(f)
{
    var options     =   {asynchronous:'true',method:'post',postBody:Form.serialize(f),parameters:{'isAjax':true},onComplete: function(t)
            {
                $('waitingSpinner').style.display   =   'none';
                $('commentForm').style.display      =   'block';
                new Insertion.Before('insertionHere',t.responseText);
            }
        };
    var url     =   f.getAttribute('action');
    var ax      =   new Ajax.Request(url,options);

    $('commentField').value =   '';

    return false;
}

function setLoad()
{
    if(req.readyState == 4 && req.status == 200)
    {
        loadValue = parseFloat(req.responseText);
        if(loadValue > 5.0 && loadValue < 13.0)
        {
            Effect.Appear('loadDivIntermediate');
			$('loadImgIntermediate').title = "load: " + loadValue;
        }

        if(loadValue > 13.0)
        {
            Effect.Appear('loadDivHigh');
			$('loadImgHigh').title = "load: " + loadValue;
        }

//        if(loadValue < 1)
//        {
//            Effect.Appear('loadDivLow');
//        }
    }
}

function doLoadingStuff()
{
//    checkLoad();
//    firdom();
//	if($('commentSubmit'))
//	{
//		$('commentSubmit').disabled = true;
//	}
}


function loadComments(currentPage, itemsPerPage)
{
    var params = '';
    if(currentPage)
    {
        params = currentPage;
        if(itemsPerPage)
        {
            params += "/" + itemsPerPage;
        }
    }
    url = '/' + objectType + '/' + objectId + '/comments/' + params;
    new Ajax.Updater('imageComments', url, { method: 'get', evalScripts: true });

}

function disableSubmit()
{
    $('commentSubmit').disabled = true;
}

window.onload=doLoadingStuff;
