String.prototype.trim = function() {

    return this.replace(/^\s+/, '').replace(/\s+$/, '');

}

function stub() {

}



function commonGet(id) {

    return document.getElementById(id);

}



function commonValidId(id) {

    return (id && commonGet(id));

}



function commonShow(id) {

    if (commonValidId(id)) {

        commonGet(id).style.display = 'block';

    }

}

function myShowBackground(id) {

    if (commonValidId(id)) {

        commonGet(id).style.background = '#ffc2a7';

    }

}

function commonShowInline(id) {

    if (commonValidId(id)) {

        commonGet(id).style.display = 'inline';

    }

}



function commonHide(id) {

    if (commonValidId(id)) {

        commonGet(id).style.display = 'none';

    }

}

function myHideBackground(id) {

    if (commonValidId(id)) {

        commonGet(id).style.background = '#ffffff';

    }

}



function commonProcessFieldError(fieldName, errorId) {

    for (var i = 0; i < 10; i++) {

        commonHide(fieldName + '_error_' + i);

    }

    commonShow(fieldName + '_' + errorId);

    return (errorId == null);

}

function commonProcessFieldError2(fieldName, errorId) {

    for (var i = 0; i < 10; i++) {

		myHideBackground(fieldName + '_error_' + i);

    }


	myShowBackground(fieldName + '_' + errorId);

    return (errorId == null);

}



function commonValidateRequired(form, fieldName, errorCode) {

    if (!form[fieldName]) {

        return true;

    }

    if (form[fieldName].value.trim().length == 0) {

        return commonProcessFieldError(fieldName, errorCode);

	} else if (form[fieldName].value == 'Write here what do you think about these photos') {

		return commonProcessFieldError(fieldName, errorCode);

    } else {

        return commonProcessFieldError(fieldName, null);

    }

}

function commonValidateRequired2(form, fieldName, errorCode) {

    if (!form[fieldName]) {

        return true;

    }

    if (form[fieldName].value.trim().length == 0) {

        return commonProcessFieldError2(fieldName, errorCode);

    } else {

        return commonProcessFieldError2(fieldName, null);

    }

}



function commonValidateEmail(form, fieldName, errorCode) {

    if (!form[fieldName]) {

        return true;

    }

    var email = /^\w[\w\-]*(\.\w[\w\-]*)*@\w[\w\-]+(\.\w[\w\-]+)*\.(a[c-gil-oq-uwz]|b[a-bd-jm-or-tvwyz]|c[acdf-ik-orsuvx-z]|d[ejkmoz]|e[ceghr-u]|f[i-kmorx]|g[abd-ilmnp-uwy]|h[kmnrtu]|i[delm-oq-t]|j[emop]|k[eg-imnprwyz]|l[a-cikr-vy]|m[acdghk-z]|n[ace-giloprtuz]|om|p[ae-hk-nrtwy]|qa|r[eouw]|s[a-eg-ort-vyz]|t[cdf-hjkm-prtvwz]|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[admrw]|com|edu|net|org|mil|gov|biz|pro|aero|coop|info|name|int|museum)$/;

    if (!email.test(form[fieldName].value)) {

        return commonProcessFieldError(fieldName, errorCode);

    } else {

        return commonProcessFieldError(fieldName, null);

    }

}

function commonValidateEmail2(form, fieldName, errorCode) {

    if (!form[fieldName]) {

        return true;

    }

    var email = /^\w[\w\-]*(\.\w[\w\-]*)*@\w[\w\-]+(\.\w[\w\-]+)*\.(a[c-gil-oq-uwz]|b[a-bd-jm-or-tvwyz]|c[acdf-ik-orsuvx-z]|d[ejkmoz]|e[ceghr-u]|f[i-kmorx]|g[abd-ilmnp-uwy]|h[kmnrtu]|i[delm-oq-t]|j[emop]|k[eg-imnprwyz]|l[a-cikr-vy]|m[acdghk-z]|n[ace-giloprtuz]|om|p[ae-hk-nrtwy]|qa|r[eouw]|s[a-eg-ort-vyz]|t[cdf-hjkm-prtvwz]|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[admrw]|com|edu|net|org|mil|gov|biz|pro|aero|coop|info|name|int|museum)$/;

    if (!email.test(form[fieldName].value)) {

        return commonProcessFieldError2(fieldName, errorCode);

    } else {

        return commonProcessFieldError2(fieldName, null);

    }

}



function commonGetAjaxParams() {

    return 'mode=async&rand=' + new Date().getTime();

}



function commonSendRequest(url, data, isPost, callback) {

    var req = null;

    if (window.XMLHttpRequest) {

        req = new XMLHttpRequest();

    } else if (window.ActiveXObject) {

        req = new ActiveXObject('Microsoft.XMLHTTP');

    }

    if (!req) {

        return null;

    }

    try {

        var postData = null;

        var method = null;

        if (isPost) {

            method = 'POST';

            postData = data;

        } else if (!data) {

            method = 'GET';

        } else if (data.length > 0) {

            method = 'GET';

            if (url.indexOf('?') >= 0) {

                url += '&' + data;

            } else {

                url += '?' + data;

            }

        }

        req.open(method, encodeURI(url), true);

        if (method == 'POST') {

            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        }

        req.onreadystatechange = function() {

            if (req.readyState == 4) {

                var xml = req.responseXML;

                if (xml && xml.documentElement) {

                    if (xml.documentElement.nodeName == 'success') {

                        callback(xml.documentElement, null);

                    } else if (xml.documentElement.nodeName == 'failure') {

                        var childs = xml.documentElement.childNodes;

                        var errors = [];

                        for (var i = 0; i < childs.length; i++) {

                            if (childs[i].nodeName == 'error') {

                                var content = null;

                                if (childs[i].textContent) {

                                    content = childs[i].textContent;

                                } else if (childs[i].innerText) {

                                    content = childs[i].innerText;

                                } else if (childs[i].text) {

                                    content = childs[i].text;

                                }

                                errors.push(content);

                            }

                        }

                        callback(null, errors);

                    }

                }

            }

        };

        req.send(postData);

    } catch (e) {

        return e;

    }

    return null;

}



// Common album func ================



var albumViewFriendFormVisible = false;

var albumViewFriendCaptcha = null;

var albumViewMyVote = null;



function albumViewEnableSendToFriend(params) {

    var stfLink = params['link_id'];

    var stfBlock = params['block_id'];

    var stfBlockSuccess = params['success_message_id'];

    var stfForm = params['form_id'];

    var stfWait = params['wait_id'];

    var albumId = params['album_id'];



    if (commonValidId(stfLink)) {

        commonGet(stfLink).onclick = function() {

            if (albumViewFriendFormVisible) {

                commonHide(stfBlock);

            } else {

                commonShow(stfBlock);

            }

            commonHide(stfBlockSuccess);

            var st1 = (albumViewFriendFormVisible ? 'collapse_link' : 'expand_link');

            var st2 = (!albumViewFriendFormVisible ? 'collapse_link' : 'expand_link');

            albumViewFriendFormVisible = !albumViewFriendFormVisible;

            if (this.className.indexOf(st1) >= 0) {

                this.className = this.className.replace(st1, st2);

            }

            return false;

        }

    }

    if (commonValidId(stfForm) && albumId) {

        commonGet(stfForm).onsubmit = function() {

            var errorField = null;

            if (!commonValidateRequired2(this, 'email', 'error_1')) {

                errorField = (errorField ? errorField : 'email');

            } else if (!commonValidateEmail2(this, 'email', 'error_1')) {

                errorField = (errorField ? errorField : 'email');

            }

            if (!commonValidateRequired2(this, 'message', 'error_1')) {

                errorField = (errorField ? errorField : 'message');

            }


            if (!errorField) {

                var form = this;

                commonSendRequest('?' + commonGetAjaxParams(), 'action=send_to_friend&album_id=' + albumId + '&email=' + encodeURIComponent(form['email'].value) + '&message=' + encodeURIComponent(form['message'].value), true, function(successNode, errorsList) {

                    if (successNode) {

                        form.reset();

                        if (commonValidId(stfLink)) {

                            commonGet(stfLink).onclick(commonGet(stfLink));

                        } else {

                            commonHide(stfBlock);

                        }

                        commonHide(stfWait);

                        commonShow(stfBlockSuccess);

                    } else if (errorsList) {

                        for (var i = 0; i < errorsList.length; i++) {

                            commonShow(errorsList[i]);

                        }

                        commonHide(stfWait);

                    }

                });

                commonShowInline(stfWait);

            } else {

                this[errorField].focus();

            }

            return false;

        }

    }

}



function albumViewEnableVoting(params) {

    var ratingContainer = params['container_id'];

    var ratingHint = params['hint_message_id'];

    var ratingSuccess = params['success_message_id'];

    var ratingFailure = params['failure_message_id'];

    var emptyImageSrc = params['empty_image_src'];

    var moverImageSrc = params['mover_image_src'];

    var imageId = params['album_image_id'];



    if (!commonValidId(ratingContainer)) {

        return;

    }

    var stars = new Array();

    var container = commonGet(ratingContainer);

    if (!container) {

        return;

    }

    var index = 1;

    for (var i = 0; i < container.childNodes.length; i++) {

        var el = container.childNodes[i];

        if (el.tagName != 'IMG') {

            continue;

        }

        el.onmouseover = function() {

            if (albumViewMyVote) {

                return;

            }

            var src = moverImageSrc;

            for (var j = 0; j < stars.length; j++) {

                stars[j]['el'].src = src;

                if (stars[j]['el'] == this) {

                    src = emptyImageSrc;

                }

            }

        };

        el.onclick = function() {

            if (albumViewMyVote) {

                return false;

            }

            var index = 0;

            for (var j = 0; j < stars.length; j++) {

                if (stars[j]['el'] == this) {

                    index = stars[j]['index'];

                    break;

                }

            }

            albumViewMyVote = index;

            commonSendRequest('?' + commonGetAjaxParams(), 'action=rate&album_image_id=' + imageId + '&vote=' + index, false, function(successNode, errorsList) {

                commonHide(ratingHint);

                if (successNode) {

					$.showMessage("Thank you for rating this album!");

                } else if (errorsList) {

					$.showMessage("You have already rated this album!");

                }

                var src = moverImageSrc;

                for (var j = 0; j < stars.length; j++) {

                    stars[j]['el'].src = src;

                    if (j == index - 1) {

                        src = emptyImageSrc;

                    }

                }

            });

        }

        stars.push({el: el, initial: el.src, index: index});

        index++;

    }

    container.onmouseout = function(e) {

        if (albumViewMyVote) {

            return;

        }

        if (!e) {

            e = window.event;

        }

        var mouseX = 0;

        var mouseY = 0;

        if (e.pageX && e.pageY) {

            mouseX = e.pageX;

            mouseY = e.pageY;

        } else if (e.clientX && e.clientY) {

            mouseX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;

            mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;

        }



        var x = 0;

        var y = 0;

        var element = container;

        while (element) {

            x += element.offsetLeft;

            y += element.offsetTop;

            element = element.offsetParent;

        }

        if ((mouseX <= x) || (mouseY <= y) || (mouseX >= x + container.offsetWidth) || (mouseY >= y + container.offsetHeight)) {

            for (var j = 0; j < stars.length; j++) {

                stars[j]['el'].src = stars[j]['initial'];

            }

        }

    };

}



function albumViewEnableAddToFavourites(params) {

    var favLink = params['link_id'];

    var favBlockSuccess = params['success_message_id'];

    var albumId = params['album_id'];



    if (commonValidId(favLink)) {

        commonGet(favLink).onclick = function() {

$.showMessage("The album has been added to your favourites.");

            commonSendRequest('?' + commonGetAjaxParams(), 'action=add_to_favourites&album_id=' + albumId, false, function(successNode) {

                if (successNode) {

                    commonHide(favLink);

                    if (commonValidId(favBlockSuccess)) {

                        commonShow(favBlockSuccess);

                    }

                }

            });

            return false;

        }

    }

}


// Album comments =================================================


var albumCommentsFormVisible = false;

var albumCommentsCaptcha = null;


function albumCommentsEnableComments(params) {

    var scLink = params['all_link_id'];

    var scBlock = params['all_block_id'];

    var acLink = params['add_link_id'];

    var acBlock = params['add_block_id'];

    var acBlockSuccess = params['success_message_id'];

    var acBlockFailure = params['failure_message_id'];

    var acForm = params['form_id'];

    var acCaptcha = params['captcha_id'];

    var acWait = params['wait_id'];

    var albumImageId = params['album_image_id'];


    if (commonValidId(scLink)) {

        commonGet(scLink).onclick = function() {

            this.style.display = 'none';

            commonShow(scBlock);

            return false;

        }

    }

    if (commonValidId(acLink)) {

        commonGet(acLink).onclick = function() {

            if (albumCommentsFormVisible) {

                commonHide(acBlock);

            } else {

                commonShow(acBlock);

            }

            commonHide(acBlockSuccess);

            commonHide(acBlockFailure);

            var st1 = (albumCommentsFormVisible ? 'collapse_link' : 'expand_link');

            var st2 = (!albumCommentsFormVisible ? 'collapse_link' : 'expand_link');

            albumCommentsFormVisible = !albumCommentsFormVisible;

            if (this.className.indexOf(st1) >= 0) {

                this.className = this.className.replace(st1, st2);

            }

            return false;

        }

    }

    if (commonValidId(acForm)) {

        commonGet(acForm).onsubmit = function() {

            var errorField = null;

            if (!commonValidateRequired(this, 'comment', 'error_1')) {

                errorField = (errorField ? errorField : 'comment');

            }

            if (!commonValidateRequired(this, 'code', 'error_5')) {

                errorField = (errorField ? errorField : 'code');

            }



            if (!errorField) {

                var form = this;

                commonSendRequest('?' + commonGetAjaxParams(), 'action=add_comment&album_image_id=' + albumImageId + '&comment=' + encodeURIComponent(form['comment'].value), true, function(successNode, errorsList) {

                    if (successNode) {

                        form.reset();

                        if (commonValidId(acLink)) {

                            commonGet(acLink).onclick(commonGet(acLink));

                        } else {



                        }

                        commonHide(acWait);

                        commonShow(acBlockSuccess);

		                $(document).ready(function(){
	
							var comments = $('#comments');

						    var action = 'showcom';

							var template = '<li>{mmm}</li>';
	
							function loadComments(){
		
								if(this != window){
									if($(this).html() == 'Loading..'){
										return false;
									}
								$(this).html('Loading..');
								}
		

								$.getJSON('/ajax.php',{'action': action, 'album_id': albumImageId},function(r){
			
								comments.find('li').show('slow', function() {

							    });
	
								$.each(r.mess,function(i,message){
									comments.append(templateReplace(template,{mmm:message}));
								});

								});

								$('textarea#commentfield').val('');
		
								return false;
							}
	
							function templateReplace(template,data){
								return template.replace(/{([^}]+)}/g,function(match,group){
								return data[group];
							});
							}

							loadComments();	
						});

                    } else if (errorsList) {

                        for (var i = 0; i < errorsList.length; i++) {

                            commonShow(errorsList[i]);

                        }

                        commonHide(acWait);

                    }

                });

                commonShowInline(acWait);

            } else {

                this[errorField].focus();

            }

            return false;

        }

    }

}

