var contentHeight;

// Resizes the search-text-input-field on the menu bar to fill the remaining space
$(window).load(function () {
    resizeSearch();
})


$(document).ready(function () {
	
	// Fill screen height with the content container
    $(window).load(function () {
        contentHeight = $('.content').height();
        setContentHeight();
		$('.bottomPane').fadeIn();

        $(window).resize(function () {
            setContentHeight();
        });
    })

	// Handle roll-over menu
	$('ul.mainMenu > li').hover(
	function(){
		$(this).parent().children('ul').css('visibility', 'visible');
		
	},
	function(){
		
		$(this).parent().children('ul').css('visibility', 'hidden');
		
	})
	
	$('ul.mainMenu > li > ul > li').hover(
	function(){
		
		$(this).children('ul').css('visibility', 'visible');
	},
	function(){
		
		
		$(this).children('ul').css('visibility', 'hidden');
		
	})

	// Call functions specific to each page
	
    switch (getUrlVarsFrom(document.location.href, true)['tabid']) {
       
    case '1':
        initHome();
        break;
    case undefined:
        initHome();
        break;
    case '5':
        initDealerCatalogue();
        break;
    case '6':
        initObjectDetail();
        break;
	case '23':
        loadVideos();
        break;
    case '28':
        loadFirstPost();
        break;
    case '44':
        fixArtistList();
        break;
    case '45':
        initArtistDetail();
        break;
    case '50':
        loadMap();
        handleContactPage();
        handleInputs();
        handleSelects();
        break;
    case '148':
		trimPosts();
        initPostListDistintion();
        adjustPostImage();
        break;
    case '149':
		initPostListDistintion();
        adjustPostImage();
        break;
    }

	// Top right menu functions
	initTopRightMenu();
	
	// Remove the placeholder text on focus
    handlePlaceHolderText();
	
	// Change style of the search-text-input-field on focus
    handleSearchInput();
	
	
    initMainMenu();
    
	// Adds a button on the bottom of the screen that takes the user to the top of the page
	addGoToTopButton();

	// Activate tooltips on elements with the tooltip class
    $('a.tooltip').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " - ",
        fade: 250
    });

	// Activate resources-submenu highlighting
    if ($('.content').hasClass('resources')) {
        highlightCurrent();
    }

	// Wishlist-related functions
    wishListFeatures();

})

function trimPosts() {
	
	$('div.postContent').each(function(index, domEle){
	
		trim(domEle, 800);
		
	})
	
}

function trim(domEl, trimmedLength) {
	if ((navigator.userAgent.indexOf("MSIE 6.") != -1) || (navigator.userAgent.indexOf("MSIE 7.") != -1) || (navigator.userAgent.indexOf("MSIE 8.") != -1)) {
		if ($(domEl).text().replace(/[\t|\n]/g,'').replace(/[  ]/g,' ').length > trimmedLength) {
			$(domEl).html($(domEl).text().substr(0,trimmedLength) + '...')
		}
	} else
	if ($(domEl).text().replace(/[\t|\n]/g,'').replace(/[  ]/g,' ').length > trimmedLength) {
		var 
			el = $(domEl),
			str = el.html(),
			strLength = str.length,
			clearStr = '',
			tag = '',
			index,
			tags = [],
			trimmedString = '',
			trimmedRealLength,
			closingTags = [],
			openTags = [];
		
		
		
		for (var i = 0, len = 0; len <= trimmedLength; i ++) {
		
			// When new tag starts, put it into the tag array
			if (str.charAt(i) == '<') {
				
				index = i;
				tag = '';
				
				while (str.charAt(i) != '>') {
				
					tag += str.charAt(i);
					
					i ++;
				}
				
				tag += str.charAt(i); // add closing tag
				
				i ++;
				
				
				tags[index] = tag;
				
			}
			
			// Add regular text to the string 
			clearStr += str.charAt(i);
			
			len = clearStr.length;
			
			if (len == trimmedLength) trimmedRealLength = i;
			
		} 
		
		// Trim regular text
		trimmedString = clearStr.substr(0,trimmedLength);
		
		// Create and add closing tags
		
		// Find Missing closure tags
		for (i in tags) { 
		
			if (i < trimmedRealLength) {
				
				//if (i == 112) alert(tags[i].slice(1,2));
				
				// if it is an opening tag, add it to the array
				if ((tags[i].slice(1,2) != '/') && (tags[i].slice(-1,1) != '/')) {
					
					if (tags[i].indexOf(' ') > -1) {
						
						openTags.push('</' + tags[i].slice(1, tags[i].indexOf(' ') ) + '>'  );
						
					} else {
						
						openTags.push('</' + tags[i].slice(1)  );
					}
				
				}
				
				// if it is a closure tag, remove the last opening tag
				if (tags[i].slice(1,2) == '/') {
				
					openTags.splice(openTags.length-1,1);
					
				}
				
				
				
			}
	
		};
		
		// insert three dots
		trimmedString += '...';
		
		// insert closure tags
		for (i in openTags.reverse()) { 
		
			trimmedString += openTags[i]; 
			
		}
		
		
		
		// Re-insert original tags
		for (i in tags) { 
		
			if (i < trimmedRealLength) {
			
				if (tags[i] != '') trimmedString = trimmedString.slice(0,i) + tags[i] + trimmedString.slice(i); 
				
			}
			
		};
		
		el.html(trimmedString);
	} 
}



function initHome(){
	
		// Remove style from blog image
	$('.blogImageStyle img').attr('style', '');
	
}

/* Search Functions */

function submitQuickSearch() {
    var keyWords = document.getElementById('inpQuickSearch').value;
    document.location.href = document.location.href.split('?')[0] + '?tabid=5&keyword=' + keyWords;
}

function submitCategory() {
    var url = document.getElementById('selCategory').value;
    document.location.href = document.location.href.substr(0, document.location.href.indexOf('DesktopDefault.aspx')) + url;
}

function entsub(e) {
    var evt = window.event ? e.keyCode : e.which;
    var keyPressed = evt;

    if (keyPressed == 13) {
        submitQuickSearch();
        return false;
    } else {
        return true;
    }
}


// Object details page
function initObjectDetail() {
	function setLinkSpacing() {

		var usedSpace = 0;
		$('div.col1 div.menu div.link').each(function (index, domEle) {
			$(domEle).css('margin-right', '0');
			usedSpace += $(domEle).width();
		});
		$('div.col1 div.menu div.link').each(function (index, domEle) {
			var margin = Math.floor(($('img.mainImage').width() - usedSpace) / 4);
			if (!$(domEle).hasClass('noMargin') || margin > 0) $(domEle).css('margin-right', margin);
		});

	var
	title = $('h2 span.title').text(),
	objectID = getUrlVarsFrom(document.location.href, false)['objectid'];;

	// Pass object data to colorbox
			
	$('div#add-to-wishlist span.object-title').html(title);
	$('div#wishlistMainBox input#object-id').val(objectID);
	
	//Enable cancel button
	$('.close-colorbox').click(function(){$.colorbox.close()})
	
	//Enable select all and select none features
	$('div#add-to-wishlist a.select-all').click(function(){
		$('div#add-to-wishlist div.list-area ul li input[type=checkbox]').attr('checked','checked')
		return false;
	})
	
	$('div#add-to-wishlist a.select-none').click(function(){
		$('div#add-to-wishlist div.list-area ul li input[type=checkbox]').attr('checked','')
		return false;
	})
	
	
	$(window).scroll(function () { 
	

	if ($(window).scrollTop() > $('td#TopPane').height()) {
		
		if ($(window).scrollTop() > $(document).height() - $(window).height() - $('div.content div.col1').height() + $('td.bottomPane div.bottom').height()) {
	
			$('div.content div.col1').css({
				'position': 'relative',
				'top': $(document).height() - $('td.topPane div.top').height() - $('div.content div.col1').height() - $('td.bottomPane div.bottom').height() - 140
			});
		
		} else {
		
		
			$('div.content div.col1').css({
				'position': 'fixed',
				'top': 0
			});
			
		}
		
	} else {
		$('div.content div.col1').css({
			'position': 'relative',
			'top': '0px'
		});
	}


	/*if (
	$(window).scrollTop() - $('td#TopPane').height() + $('div.content div.col1').height() < $('div.content div.col2').height() && 
	$('div.content div.col1').height() < $(window).height()) {
		
		$('div.content div.col1').css({
			'position': 'fixed',
			'top': '0px'
		});
	
	
	
	} else {
	
		//$('div.content div.col1').stop().animate({marginTop:0},{duration:800,queue:false});
		$('div.content div.col1').css({
			'position': 'relative',
			'top': '0px'
		});
	}
	if ($(window).scrollTop() > $(document).height() - $('div.content div.col1').height() - $('td.bottomPane div.bottom').height()) {
	
		$('div.content div.col1').css({
			'position': 'absolute',
			'bottom': '0px'
		});
	
	}
	*/
	});

}


/*$('.mainImage').load(function(){
		if ($('table.additionalImages td img').length > 2) {
			$($('table.additionalImages td')[1]).css('width', '100%');
			$($('table.additionalImages td')[0]).css({'text-align': 'left', 'width': 0});
			$($('table.additionalImages td')[1]).css('text-align', 'center');
			$($('table.additionalImages td')[2]).css({'text-align': 'right', 'width': 0});
			$('table.additionalImages').width($('.mainImage').width());
		}
	});*/
	$('div#referenceCopy').html($('span.reference').html());

	$(window).load(function () {
		setLinkSpacing();
	})
}


// Differentiate the news page from the articles page
function initPostListDistintion() {
	
	if (getUrlVarsFrom(document.location.href, true)['postcategoryid'] == '181') {
		
		$('div.content').addClass('news').removeClass('resources');
		
	} else {
	
		$('div.content').addClass('articles');
		
	}
}

// Top right menu functions
function initTopRightMenu(){
	showLogInForm();
	showNewsletterSubscription();
}

// Display the mail list subscription form on the top right menu when 'Join our mailing list' is clicked
function showLogInForm() {
	$('#log-in-button').click(function(){
		$('li.newsletter-subscription iframe').hide();
		$('li.log-in div.top-log-in-form').toggle();
		
			$(document).bind('click.toggleLogInForm', function(e) { 
			
				if( 
				(e.pageX < $('li.log-in div.top-log-in-form').offset().left) ||
				(e.pageX > $('li.log-in div.top-log-in-form').offset().left + $('li.log-in div.top-log-in-form').width())  ||
				(e.pageY < $('li.log-in div.top-log-in-form').offset().top) ||
				(e.pageY > $('li.log-in div.top-log-in-form').offset().top + $('li.log-in div.top-log-in-form').height()) 
				
				) {
      				$('li.log-in div.top-log-in-form').hide();
					
					$(document).unbind('click.toggleLogInForm');
				}
			});
		return false;
	});
}

// Display the log-in form on the top right menu when 'Log in' is clicked
function showNewsletterSubscription() {
	$('#join-mail-list-button').click(function(){
		$('li.log-in div.top-log-in-form').hide();
		$('li.newsletter-subscription iframe').toggle();
		
			$(document).bind('click.toggleNewsletterMenu', function(e) { 
			
				if( 
				(e.pageX < $('li.newsletter-subscription iframe').offset().left) ||
				(e.pageX > $('li.newsletter-subscription iframe').offset().left + $('li.newsletter-subscription iframe').width())  ||
				(e.pageY < $('li.newsletter-subscription iframe').offset().top) ||
				(e.pageY > $('li.newsletter-subscription iframe').offset().top + $('li.newsletter-subscription iframe').height()) 
				
				) {
      				$('li.newsletter-subscription iframe').hide();
					
					$(document).unbind('click.toggleNewsletterMenu');
				}
			});
		return false;
	});
}



//Wish list features

function wishListFeatures() {

    if ($('div.page.edit.wishlist').length > 0) {
        // Wish-list edition page ---------------------
        // handle title edition
        $('div.title a#edit-title').click(function () {

            $('span.title-content').html('<input type="text" value="' + $('span.title-content').text() + '" name="txtWishTitle">');
            $('div.title #save-title').show();
            $('div.title #edit-title').hide();
            return false;

        });
        $('div.title a#save-title').click(function () {

            $('span.title-content').html($('div.title input').val());
            $('div.title #edit-title').show();
            $('div.title #save-title').hide();
            return false;

        });

        // handle list edition
        $('a#delete-object').click(function () {
            function removeObject(obj) {

                $(obj).parents('div.row').fadeOut();

            }

            var deleteObj = window.confirm($(this).parents('div.row').find('div.buttons input#delObjText').val())
            if (deleteObj) {
				removeObject(this);
				__doPostBack($(this).parents('div.row').find('div.buttons input#hdnControl').val(), $(this).parents('div.row').find('div.buttons input#hdnObjectID').val());
			}

            return false;

        });

    } else if ($('div.form-area').length > 0) {
        // Wish-list login page ---------------------
        handleInputs();
    }
}



//Init video page


function initVideoPage() {
    VideoJS.setupAllWhenReady();
}

//MENU FUNCTIONS


function nrKeys(a) {
    var i = 0;
    for (key in a) {
        i++;
    }
    return i;
}

function compareAssociativeArrays(a, b) {
    if (a == b) {
        return true;
    }
    if (nrKeys(a) != nrKeys(b)) {
        return false;
    }
    for (key in a) {
        if (a[key] != b[key]) {
            return false;
        }
    }
    return true;
}


//highlight current item on menu for the resources page


function highlightCurrent() {
    //check for matches on menu
    $("div.leftMenu a").each(function (index, domEle) {

        if (compareAssociativeArrays(getUrlVarsFrom(window.location.href, 1), getUrlVarsFrom($(domEle).attr('href'), 1))) {

            $(domEle).addClass('active');
        }


    });


}


// load first post
function loadVideos() {

    var address = 'media/adrianAlanMedia/includes/videos.shtml';

    /*$("<div>").load(address + ' div.content', function () {

        $('div.content').append($(this).html());
       
	   
	   
    });*/


}


// load first post
function loadFirstPost() {

    var address = 'DesktopDefault.aspx?tabid=148&tabindex=147&postcategoryid=182';

    $("<div>").load(address + ' div.resourcesContent', function () {



        $('div#article div.textArea .text').append($(this).find('div.postTemplate:first h2.blogTitle'));
        $('div#article div.textArea .text').append($(this).find('div.postTemplate:first div.postContent').text());
        $('div#article div.textArea .text').append($(this).find('div.postTemplate:first a.readmore'));
        $('div#article div.imageArea').append($(this).find('div.postTemplate:first img:first'));
        fixArtistList();
    });


}

//resize search-input 
function resizeSearch() {
    var usedSpace = 0;
    $('ul.mainMenu > li:last').addClass('last');
    $('ul.mainMenu > li').each(function (index, domEle) {

        if (!$(domEle).hasClass('last')) usedSpace += $(domEle).width() + parseInt($(domEle).css("padding-right"), 10) + parseInt($(domEle).css("padding-left"), 10);


    })
    //alert(usedSpace);
    $('ul.mainMenu > li.search > input').width(960 - (usedSpace + 39));
    $('ul.mainMenu > li.search').width(960 - (usedSpace + 36 - 12))
}

function initMainMenu() {
    $('ul.mainMenu > li > ul').each(function (index, domEle) {

        $('li:first', domEle).addClass('first');
        $('li:last', domEle).addClass('last');

    })
}

function addGoToTopButton() {
    $('.content').append('<a title="Go to Top" href="#top" class="top-of-page tooltip"></a>');
    $('a.top-of-page').click(function () {
        $(window).scrollTop(0);
        return false;
    });
    if ($(window).scrollTop() == 0) {
        $('a.top-of-page').hide();
    }
    $(window).scroll(function () {
        if ($(window).scrollTop() < $(document).height() - $(window).height() - $('#BottomPane').height()) {
            $('a.top-of-page').css({'position':'fixed', 'bottom': '0px'});
        } else {
			$('a.top-of-page').css({'position':'absolute', 'bottom': 0});
            //$('a.top-of-page').css('top',  $(document).height() -$('#BottomPane').height()  - $('#TopPane').height() - 28);
        }
        if ($(window).scrollTop() == 0) {
            $('a.top-of-page').hide();
        } else {
            if ($('a.top-of-page').css('display') == 'none') {
                $('a.top-of-page').show();
            }
        }
    });

}

function handleSearchInput() {

    $('input.search').focus(function () {
        $('li.search *').css('background-position', 'top left');
        $('li.search').addClass('focus');
    });

    $('input.search').blur(function () {
        $('li.search *').css('background-position', 'left -23px');
        $('li.search').removeClass('focus');
    });

}

function fixArtistList() {
    $('table.nameList a').each(function (index, domEle) {
        if ($(domEle).attr('href') === undefined) {

            $(domEle).replaceWith($(domEle).html());
        }
    })

}

// map functions (contact page)

function loadMap() {
    if (GBrowserIsCompatible()) {
        var map1 = new GMap2(document.getElementById("map1"));
        var point = new GLatLng(51.508687, -0.151518);
        map1.setCenter(point, 15);
        var marker = new GMarker(point);
        map1.addOverlay(marker);
        map1.addControl(new GSmallMapControl());




    }
}

function handleInputs() {


    //handle text input
	function handleTextInput(index, domEle){
		
		 var target;
        if ($(domEle).children('input').length > 0) {
            target = 'input';
        } else {
            target = 'textarea'
        }

        if ($('label', domEle).length == 0) {
            $(domEle).append('<label />');
            $('label', domEle).html($('.label', domEle).html().replace(':', ''));
            $('span.label', domEle).remove();
        }
        $('label', domEle).attr('for', $(target, domEle).attr('id'));





        if ($(target, domEle).val() != '') {
            $('label', domEle).css('display', 'none');
        }
        $(target, domEle).focus(function () {
            if ($(this).val() == '') {
                $('label', domEle).animate({
                    opacity: 0.25
                }, 250);
            }
        });

        $(target, domEle).blur(function () {
            if ($(this).val() == '') {
                $('label', domEle).css('display', 'block');
                $('label', domEle).animate({
                    opacity: 1
                }, 250);

            }
        });
        $(target, domEle).keydown(function () {

            $('label', domEle).css('display', 'none');

        });

        $(target, domEle).change(function () {
            if ($(this).val() == '') {
                $('label', domEle).css('opacity', 1);

            }
        });

		
	}
	
    $('.inputBox').each(function (index, domEle) {

       handleTextInput(index, domEle);

    });
	 $('.form-area .text').each(function (index, domEle) {
		
        handleTextInput(index, domEle);

    });
}

function handleSelects() {
    //handle select
    $('select.selectBox').parent().prepend('<div class="selectBoxMask" />').prepend('<label />');
    $('select.selectBox').parent().children('label').attr('for', $('select.selectBox').attr('id')).addClass('label').attr('style', '');
    $('select.selectBox').css('opacity', 0);
    $('select.selectBox').change(function () {
        var val = $(this).find('option:selected').text();
        $('select.selectBox').parent().children('label').html(val);
    });


    // anulate hidden status from comment label
    $('inputBox.comments label').attr('style', '');

}

function handleContactPage() {
    // hide confirmation span if it has no content
    if ($('span.confirmation').is(":empty")) $('span.confirmation').css('display', 'none');
    $('span.req').each(function (index, domEle) {
        if ($(domEle).css('visibility') == 'hidden') $(domEle).css('display', 'none');

    })


    $('.inputBox.select label').html($('.inputBox.select select option:first').html());


}


function initArtistDetail()  {
    $('table.objectTable td a img').each(function (index, domEle) {


        $(domEle).parent().attr('title', $(domEle).parent().parent().children('span.artistName').text() + ' - ' + $(domEle).parent().parent().children('span.title').text()).addClass('tooltip');
    });
}


var marginsSet = 0;

function setMargins() {
    marginsSet = 1;

    var rowWidth = 0,
        row = 0,
        col = -2;
    for (var i = 0; i < $('ul#catalogue li').length; i++) {
        col += 1;
        rowWidth += $($('ul#catalogue li a img')[i]).width();

        if (rowWidth + (15 * (col + 1)) > 960) {

            $('ul#catalogue li.row' + row).css('margin-right', Math.floor((960 - (rowWidth - $($('ul#catalogue li a img')[i]).width())) / (col)));
            col = -1;


            row += 1;
            rowWidth = $($('ul#catalogue li a img')[i]).width();

            $($('ul#catalogue li')[i - 1]).addClass('last');

        }

        $($('ul#catalogue li')[i]).addClass('row' + row);

    }
    $('ul#catalogue li.last').css('margin-right', 0);

}

var loaded = 0;

function initDealerCatalogue() {



    $('table.objectTable td a img').each(function (index, domEle) {

        $('ul#catalogue').append('<li />');

		var 
			title = $(domEle).parent().parent().children('span.title').text(),
			artist = $(domEle).parent().parent().children('span.artistName').text(),
			objectID = getUrlVarsFrom($(domEle).parent().attr('href'), false)['objectid'];
		
        $(domEle).parent().attr('title', artist + ' - ' + title).addClass('tooltip');



        $(domEle).parent().appendTo('ul#catalogue li:last');

        $('ul#catalogue li:last').append('<a href="#" title="Add to Wish-list!" class="wishList tooltip"></a>');

		if ($(domEle).hasClass('selected')) {
			$('ul#catalogue li:last a.wishList').addClass('selected').fadeTo(300, 1);
			
		}

        $(domEle).hover(function () {

            $(domEle).parent().parent().children('.wishList').stop().fadeTo(300, 1);

        }, function () {
            if (!$(domEle).parent().parent().children('.wishList').hasClass('selected')) {
                $(domEle).parent().parent().children('.wishList').stop().fadeTo(300, 0);
            }
        })

        $(domEle).parent().parent().children('.wishList').hover(function () {

            $(domEle).parent().parent().children('.wishList').stop();

            if ($(domEle).parent().parent().children('.wishList').css('opacity') != 1) {

                $(domEle).parent().parent().children('.wishList').stop().fadeTo(300, 1);
            }



        }, function () {
            if (!$(domEle).parent().parent().children('.wishList').hasClass('selected')) {
                $(domEle).parent().parent().children('.wishList').stop().fadeTo(300, 0);
            }
        })

        $(domEle).parent().parent().children('.wishList').click(function () {
			$('div#add-to-wishlist div.list-area ul li input[type=checkbox]').attr('checked','');
			cblWishList_callback(objectID);

            /*if ($(this).hasClass('selected')) {

                $('div.top span.wishListItemQuantity').html(parseInt($('div.top span.wishListItemQuantity').text()) - 1);

            } else {
                $('div.top span.wishListItemQuantity').html(parseInt($('div.top span.wishListItemQuantity').text()) + 1);

            }

            $(this).toggleClass('selected');*/
			
			
			// Pass object data to colorbox
			
			$('div#add-to-wishlist span.object-title').html(title);
			$('div#wishlistMainBox input#object-id').val(objectID);
			
			
			//Enable cancel button
			$('.close-colorbox').click(function(){$.colorbox.close()})
			
			//Enable select all and select none features
			$('div#add-to-wishlist a.select-all').click(function(){
				$('div#add-to-wishlist div.list-area ul li input[type=checkbox]').attr('checked','checked')
				return false;
			})
			
			$('div#add-to-wishlist a.select-none').click(function(){
				$('div#add-to-wishlist div.list-area ul li input[type=checkbox]').attr('checked','')
				return false;
			})
			
			// Reset Colorbox window when new colorbox is opened
            
			
        })

        $(window).load(function () {
            if (marginsSet == 0) setMargins();
        });

        $(domEle).load(function () {
            loaded += 1;

            if (loaded == $('ul#catalogue li').length) {


                if (marginsSet == 0) setMargins();


            }
        });

    });
	
	
	
	
}

function handlePlaceHolderText() {
    $('input[type=text]').focus(function () {
        if ($(this).val() == $(this).attr('defaultValue')) {
            $(this).val('');

        }
    });

    $('input[type=text]').blur(function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr('defaultValue'));

        }
    });


    $('textarea').focus(function () {
        if ($(this).val() == $(this).attr('defaultValue')) {
            $(this).val('');

        }
    });

    $('textarea').blur(function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr('defaultValue'));

        }
    });

}


// Set minimum page size, so that the footer gets on the bottom

function setContentHeight() {
    var headerHeight, footerHeight = 328;
    headerHeight = $('.top').length > 0 ? 180 : 0;
    if ($(window).height() - headerHeight - footerHeight > contentHeight) {
        $('.contentPane').css('height', $(window).height() - headerHeight - footerHeight + 'px')
    } else {
        $('.contentPane').css('height', '')
    };

}


// Set Blog image margins
function adjustPostImage() {

    $('p.blogImageStyle img').each(function (index, domEle) {

        if ($(domEle).css('float') == 'right') $(domEle).css('margin-right', 10);
        if ($(domEle).css('float') == 'left') $(domEle).css('margin-left', 0);
    });
}

// Get variables from the url
function getUrlVarsFrom(url, preventUnwantedVars) {
    var vars = [],
        hash;
    var hashes = url.split('#')[0].slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        if (preventUnwantedVars == 1) {
            if (hash[0] != 'lg' && hash[0] != 'objectid' && hash[0] != 'tabindex' && hash[0] != 'page' && hash[0] != 'keyword' && hash[0] != 'mediaid') {
                if (hash[0] == 'categoryid' && hash[1] == 0) {} else {
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
            }
        } else {
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
    }
    return vars;
}


/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;
(function ($) {
    var helper = {},
        current, title, tID, IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
        track = false;
    $.tooltip = {
        blocked: false,
        defaults: {
            delay: 200,
            fade: false,
            showURL: true,
            extraClass: "",
            top: 15,
            left: 15,
            id: "tooltip"
        },
        block: function () {
            $.tooltip.blocked = !$.tooltip.blocked;
        }
    };
    $.fn.extend({
        tooltip: function (settings) {
            settings = $.extend({}, $.tooltip.defaults, settings);
            createHelper(settings);
            return this.each(function () {
                $.data(this, "tooltip", settings);
                this.tOpacity = helper.parent.css("opacity");
                this.tooltipText = this.title;
                $(this).removeAttr("title");
                this.alt = "";
            }).mouseover(save).mouseout(hide).click(hide);
        },
        fixPNG: IE ?
        function () {
            return this.each(function () {
                var image = $(this).css('backgroundImage');
                if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
                    image = RegExp.$1;
                    $(this).css({
                        'backgroundImage': 'none',
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
                    }).each(function () {
                        var position = $(this).css('position');
                        if (position != 'absolute' && position != 'relative') $(this).css('position', 'relative');
                    });
                }
            });
        } : function () {
            return this;
        },
        unfixPNG: IE ?
        function () {
            return this.each(function () {
                $(this).css({
                    'filter': '',
                    backgroundImage: ''
                });
            });
        } : function () {
            return this;
        },
        hideWhenEmpty: function () {
            return this.each(function () {
                $(this)[$(this).html() ? "show" : "hide"]();
            });
        },
        url: function () {
            return this.attr('href') || this.attr('src');
        }
    });

    function createHelper(settings) {
        if (helper.parent) return;
        helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();
        if ($.fn.bgiframe) helper.parent.bgiframe();
        helper.title = $('h3', helper.parent);
        helper.body = $('div.body', helper.parent);
        helper.url = $('div.url', helper.parent);
    }

    function settings(element) {
        return $.data(element, "tooltip");
    }

    function handle(event) {
        if (settings(this).delay) tID = setTimeout(show, settings(this).delay);
        else show();
        track = !! settings(this).track;
        $(document.body).bind('mousemove', update);
        update(event);
    }

    function save() {
        if ($.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler)) return;
        current = this;
        title = this.tooltipText;
        if (settings(this).bodyHandler) {
            helper.title.hide();
            var bodyContent = settings(this).bodyHandler.call(this);
            if (bodyContent.nodeType || bodyContent.jquery) {
                helper.body.empty().append(bodyContent)
            } else {
                helper.body.html(bodyContent);
            }
            helper.body.show();
        } else if (settings(this).showBody) {
            var parts = title.split(settings(this).showBody);
            helper.title.html(parts.shift()).show();
            helper.body.empty();
            for (var i = 0, part;
            (part = parts[i]); i++) {
                if (i > 0) helper.body.append("<br/>");
                helper.body.append(part);
            }
            helper.body.hideWhenEmpty();
        } else {
            helper.title.html(title).show();
            helper.body.hide();
        }
        if (settings(this).showURL && $(this).url()) helper.url.html($(this).url().replace('http://', '')).show();
        else helper.url.hide();
        helper.parent.addClass(settings(this).extraClass);
        if (settings(this).fixPNG) helper.parent.fixPNG();
        handle.apply(this, arguments);
    }

    function show() {
        tID = null;
        if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
            if (helper.parent.is(":animated")) helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
            else helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
        } else {
            helper.parent.show();
        }
        update();
    }

    function update(event) {
        if ($.tooltip.blocked) return;
        if (event && event.target.tagName == "OPTION") {
            return;
        }
        if (!track && helper.parent.is(":visible")) {
            $(document.body).unbind('mousemove', update)
        }
        if (current == null) {
            $(document.body).unbind('mousemove', update);
            return;
        }
        helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
        var left = helper.parent[0].offsetLeft;
        var top = helper.parent[0].offsetTop;
        if (event) {
            left = event.pageX + settings(current).left;
            top = event.pageY + settings(current).top;
            var right = 'auto';
            if (settings(current).positionLeft) {
                right = $(window).width() - left;
                left = 'auto';
            }
            helper.parent.css({
                left: left,
                right: right,
                top: top
            });
        }
        var v = viewport(),
            h = helper.parent[0];
        if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
            left -= h.offsetWidth + 20 + settings(current).left;
            helper.parent.css({
                left: left + 'px'
            }).addClass("viewport-right");
        }
        if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
            top -= h.offsetHeight + 20 + settings(current).top;
            helper.parent.css({
                top: top + 'px'
            }).addClass("viewport-bottom");
        }
    }

    function viewport() {
        return {
            x: $(window).scrollLeft(),
            y: $(window).scrollTop(),
            cx: $(window).width(),
            cy: $(window).height()
        };
    }

    function hide(event) {
        if ($.tooltip.blocked) return;
        if (tID) clearTimeout(tID);
        current = null;
        var tsettings = settings(this);

        function complete() {
            helper.parent.removeClass(tsettings.extraClass).hide().css("opacity", "");
        }
        if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
            if (helper.parent.is(':animated')) helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
            else helper.parent.stop().fadeOut(tsettings.fade, complete);
        } else complete();
        if (settings(this).fixPNG) helper.parent.unfixPNG();
    }
})(jQuery);
