
// Display a warning message which has to be confirmed or cancelled
function warning(message) {
    if (confirm(message)) {
        return true;
    }
    else {
        return false;
    }
}

// Get the value from a url parameter and return it
function getUrlParameter(url, parameter) {
    var regexS = "[\\?&]"+parameter+"=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null) {
        return "";
    }
    else {
        return results[1];
    }
}

// On window load initializers
Event.observe(window, 'load', addToListInit);

Event.observe(window, 'load', removeFromListInit);

Event.observe(window, 'load', showListsContainingContentLinkObserve);

Event.observe(window, 'load', function(e) { 
	if ($('showEditListTitle')) {
		$('showEditListTitle').hide();
	}
});



Event.observe(window, 'load', setWebSafeNameFormInit);

function setWebSafeNameFormInit() {
    // if element exists
    if ($('setWebSafeNameForm')) {
        Event.observe('setWebSafeNameForm', 'submit', setWebSafeName);
    }
}

function setWebSafeName(e) {
	var url = $('setWebSafeNameForm').getAttribute('action');
	url = url + '&ajax=1';
    // for disabling header/footer in the page call


	var params = $('setWebSafeNameForm').serialize(true);
	
	
	new Ajax.Request(url, { parameters: params, onSuccess: function(x) {
		$('setWebSafeNameErrorMessages').update(x.responseText);
	}});
	
	// Stop form from submitting when JavaScript is enabled
	Event.stop(e);
}





Event.observe(window, 'load', setProfileWidgetsFormInit);

function setProfileWidgetsFormInit() {
    // if element exists
    if ($('setProfileWidgetsForm')) {
        Event.observe('setProfileWidgetsForm', 'submit', function(e) {
        	
        	var url = $('setProfileWidgetsForm').getAttribute('action');
			//url = url + '&ajax=1';			
    		// for disabling header/footer in the page call
        	
        	var params = $('setProfileWidgetsForm').serialize(true);
	
			new Ajax.Request(url, { parameters: params, onSuccess: function(e1) {
								
				if (!$F('widget_lists')) {
					if($('profileWidgetLists')) {
						$('profileWidgetLists').hide();
					}
        		}
        		else {
        			if($('profileWidgetLists')) {
						$('profileWidgetLists').show();
					}
        		}
        		
        		if (!$F('widget_ratings')) {
					if($('profileWidgetRatings')) {
						$('profileWidgetRatings').hide();
					}
        		}
        		else {
        			if($('profileWidgetRatings')) {
						$('profileWidgetRatings').show();
					}
        		}
        		
        		if (!$F('widget_forum')) {
					if($('profileWidgetForum')) {
						$('profileWidgetForum').hide();
					}
        		}
        		else {
        			if($('profileWidgetForum')) {
						$('profileWidgetForum').show();
					}
        		}
        		
        		if (!$F('widget_comments')) {
					if($('profileWidgetComments')) {
						$('profileWidgetComments').hide();
					}
        		}
        		else {
        			if($('profileWidgetComments')) {
						$('profileWidgetComments').show();
					}
        		}
        		
				updateBox('Endringene er lagret.');
				showBox();
				hideBoxTimed(2000);

			}});
			
			// Stop form from submitting when JavaScript is enabled
			Event.stop(e);

        });
		
    }
}

Event.observe(window, 'load', editListTitleFormInit);

function editListTitleFormInit() {
    // if element exists
    if ($('editListTitleForm')) {
        Event.observe('editListTitleForm', 'submit', editListTitle);
    }
}

function editListTitle(e) {
	var url = $('editListTitleForm').getAttribute('action');
	url = url + '&ajax=1';
    // for disabling header/footer in the page call


	var params = $('editListTitleForm').serialize(true);
	
	
	new Ajax.Request(url, { parameters: params, onSuccess: function(x) {
		$('editListTitleErrorMessages').update(x.responseText);
	}});
	
	// Stop form from submitting when JavaScript is enabled
	Event.stop(e);
}


Event.observe(window, 'load', changeUserProfilePrivateInit);

function changeUserProfilePrivateInit() {
    // if element exists
    if ($('changeUserProfilePrivateLink')) {
        Event.observe('changeUserProfilePrivateLink', 'click', changeUserProfilePrivate);
    }
}

function changeUserProfilePrivate(e) {
	var url = $('changeUserProfilePrivateLink').getAttribute('href');
	url = url + '&ajax=1';
    // for disabling header/footer in the page call

	new Ajax.Request(url, {onSuccess: function(x) {
		$('changeUserProfilePrivateLink').remove();
		$('changeUserProfilePrivateResponse').update(x.responseText);
	}});
	
	// Stop link from submitting when JavaScript is enabled
	Event.stop(e);
}



function popUpLogin(redirectUrl) {
	$('box').update('Denne funksjonen krever at du er innlogget. Se login-boks i menyen til venstre. Brukernavn og passord er det samme som på forumet.'); 
	showBox();
}



Event.observe(window, 'load', rateIt);

function rateIt() {
	// if element exists
    if ($('rating')) {
		// add an event observer to each rating link
		
		$('rating').select('a').each(function(link) {
			
			Event.observe(link, 'click', function(e) {
				
				var url = link.href;
				
				var myClass = link.className;
				
				
				if (myClass == 'notLogged') {
					var redirectUrl = getUrlParameter(url, 'redirect');
					popUpLogin(redirectUrl);
				}
				else {
				
				
				var productID = getUrlParameter(url, 'pid');
				//var reviewID = getUrlParameter(url, 'rid');
				url = url + '&ajax=1';
    			// for disabling header/footer in the page call
				
				//alert(url);
				
				new Ajax.Request(url, {onComplete: function() {
					var urlArray = url.split("?");
					var pageUrl = urlArray[0];
					url = pageUrl + '?do=ajaxRefreshRatingElement&pid='+ productID + '&ajax=1';
					//alert(url);
					new Ajax.Updater('rating', url, {onComplete: function() {
						rateIt();
					}});
					}
				});
				
				}
				
				
				
				Event.stop(e);	
    		});
			
        	
    		
    		
			
		});
	
	
	}
}


function refreshYourListsContainingContent(mainTypeID, genericID) {
    
	var url = '/list.php?do=showYourListsContainingContent&mid='+ mainTypeID +'&gid='+ genericID;
	
    url = url + '&ajax=1';
    // for disabling header/footer in the page call

    new Ajax.Request(url, { method: 'get', onSuccess: function(x) {
		Element.replace('yourListsContainingThisContent', x.responseText);
		removeFromListInit();
	}});

}


function showListsContainingContentLinkObserve() {
    // if element exists
    if ($('showListsContainingContentLink')) {
        Event.observe($('showListsContainingContentLink'), 'click', function(e) {
            var url = $('showListsContainingContentLink').getAttribute('href');


                url = url + '&ajax=1';
                // for disabling header/footer in the page call

                new Ajax.Request(url, {method: 'get', onSuccess: function(x) {
					Element.replace('listsContainingThisContent', x.responseText);

					$('showListsContainingContentLink').update('skjul');
					
					Event.observe($('showListsContainingContentLink'), 'click', function(e) {
						if ($('listsContainingThisContent').down('ul')) {
							$('listsContainingThisContent').down('ul').remove();
						}
						$('showListsContainingContentLink').update('vis');
						showListsContainingContentLinkObserve();
						Event.stop(e);
            			// Stop link from executing "old style"	
					});
					

                }});

            Event.stop(e);
            // Stop link from executing "old style"
        });
    }
}



function removeFromListInit() {
    // add an event observer to each delete link
	var removeFromListLinks = $$('.removeFromListLink');
    removeFromListLinks.each(function(link) {
        removeFromListLinkObserve(link.id);
    });
}

// removeFromList
function removeFromListLinkObserve(linkId) {
    // if element exists
    if ($(linkId)) {
        Event.observe($(linkId), 'click', function(e) {
            var url = $(linkId).getAttribute('href');

            var listID = getUrlParameter(url, 'lid');
			var mainTypeID = getUrlParameter(url, 'mid');
			var genericID = getUrlParameter(url, 'gid');
            if (warning('Er du sikker på at du vil fjerne dette elementet fra denne lista?')) {

                url = url + '&ajax=1';
                // for disabling header/footer in the page call

                new Ajax.Updater('box', url, {method: 'get', onSuccess: function() {
					//showBox();
					if ($('removeFromList_' + listID + '_' + mainTypeID + '_' + genericID)) {
						$('removeFromList_' + listID + '_' + mainTypeID + '_' + genericID).remove();
					}
					
					if ($('listElement_' + mainTypeID + '_' + genericID)) {
						$('listElement_' + mainTypeID + '_' + genericID).remove();
					}
					
                }});
            }
            Event.stop(e);
            // Stop link from executing "old style"
        });
    }
}




function addToListInit() {
    // if element exists
    if ($('addToListLink')) {
        Event.observe($('addToListLink'), 'click', function(e) {
            var url = $('addToListLink').getAttribute('href');
			//alert(url);
            url = url + '&ajax=1';
            // for disabling header/footer in the page call

            new Ajax.Updater('box', url, {onComplete: function() {
                addToListFormInit();

                //addCategoryLinkObserve();

                // display "lightbox"
                showBox();
            }});

            Event.stop(e);
            // Stop link from executing "old style"
        });
    }
}

function addToListFormInit() {
    // if element exists
    if ($('addToListForm')) {
        Event.observe('addToListForm', 'submit', addList);
    }

	if ($('addToListAction0')) {
		
		Event.observe($('addToListAction0'), 'click', function(e) {
			if ($('addToListNewListTitle')) {
				$('addToListNewListTitle').hide();
			}
			if ($('addToListNewListComment')) {
				$('addToListNewListComment').hide();
			}
		});
		
	}
	if ($('addToListAction1')) {
		Event.observe($('addToListAction1'), 'click', function(e) {
			if ($('addToListNewListTitle')) {
				$('addToListNewListTitle').show();
			}
			if ($('addToListNewListComment')) {
				$('addToListNewListComment').show();
			}
		});
		
	}
}



function addList(e) {
	if ($('addToListForm')) {
		var url = $('addToListForm').getAttribute('action');
	    url = url + '&ajax=1';
	    // for disabling header/footer in the page call
	
		var params = $('addToListForm').serialize(true);

		var mainTypeID = params['maintype_id'];
		var genericID = params['generic_id'];


		var urlArray = url.split("?");
		var pageUrl = urlArray[0];
	
	
		new Ajax.Request(url, { parameters: params, onSuccess: function(e1) {
			
			if (e1.responseText.substring(0,6) == '_TRUE_') {
				addToListFormInit();
				refreshYourListsContainingContent(mainTypeID, genericID);
				updateBox('Lagt til i valgt liste');
				hideBoxTimed(2000);
			}
			else {
				if ($('addToListErrorMessages')) {
					var response = e1.responseText.replace(/_TRUE_/, '');
					//$('addToListErrorMessages').innerHTML = e1.responseText;
					$('addToListErrorMessages').update(response);
				}
			}

		}});

	    // Stop form from submitting when JavaScript is enabled
	    Event.stop(e);
	
	}
	
}



// http://www.pjhyett.com/posts/190-the-lightbox-effect-without-lightbox

function updateBox(content) {
	$('box').update(content);
}

function showBox(){
    //$('overlay').show();
    center('outerBox');
    $('box').show();
    //center('box');
    return false;
}

function hideBoxTimed(wait) {
	setTimeout("hideBox()", wait);
    return false;
}


function hideBox() {
	$('outerBox').hide();
    $('box').hide();
    //$('overlay').hide();
    return false;
}

function center(element){
    try{
        element = $(element);
    }catch(e){
        return;
    }

    var my_width  = 0;
    var my_height = 0;

    if ( typeof( window.innerWidth ) == 'number' ){
        my_width  = window.innerWidth;
        my_height = window.innerHeight;
    }else if ( document.documentElement &&
             ( document.documentElement.clientWidth ||
               document.documentElement.clientHeight ) ){
        my_width  = document.documentElement.clientWidth;
        my_height = document.documentElement.clientHeight;
    }
    else if ( document.body &&
            ( document.body.clientWidth || document.body.clientHeight ) ){
        my_width  = document.body.clientWidth;
        my_height = document.body.clientHeight;
    }

    element.style.position = 'absolute';
    element.style.zIndex   = 99;

    var scrollY = 0;

    if ( document.documentElement && document.documentElement.scrollTop ){
        scrollY = document.documentElement.scrollTop;
    }else if ( document.body && document.body.scrollTop ){
        scrollY = document.body.scrollTop;
    }else if ( window.pageYOffset ){
        scrollY = window.pageYOffset;
    }else if ( window.scrollY ){
        scrollY = window.scrollY;
    }

    var elementDimensions = Element.getDimensions(element);

    var setX = ( my_width  - elementDimensions.width  ) / 2;
    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

    setX = ( setX < 0 ) ? 0 : setX;
    //setY = ( setY < 0 ) ? 0 : setY;
    // tor: set y
    setY = 200;

    element.style.left = setX + "px";
    element.style.top  = setY + "px";

    element.style.display  = 'block';
}


function wait(msecs) {
	var start = new Date().getTime();
	var cur = start
	while(cur - start < msecs) {
		cur = new Date().getTime();
	}
}

