/*global $, window, FCKeditorAPI */

/************************/
// captcha
/************************/
function randImg() {
    
    $('#code').attr('autocomplete', 'off');
    $('#abc').html('Loading...');
    $.ajax({
        url : '/vision/randimg/img/',
        success : function (img) {
            $('#abc').html(img); 
            return true;
        }
    });
    
};


/************************/
// adjust footer height
/************************/
function footerHeight() {
    
    var footerHTML, heightCalc;
    
    footerHTML = document.getElementById('vision-foot');
    heightCalc = document.documentElement.clientHeight - (footerHTML.offsetTop + 54);
    
    //alert(heightCalc);
    
    if (heightCalc > 45) {
        footerHTML.style.height = heightCalc + 'px';
    } else {
        footerHTML.style.height = 'auto';
    }
    
};


/************************/
// set status
/************************/
function visionSetStatus(nClass, nWidth) {
    
    if ($('#status').length > 0) {
        
        $('#status').css({
            MozBorderRadius : '5px',
            WebkitBorderRadius : '5px'
        });
        
        // default status bob size
        if (typeof nWidth === 'undefined') {
            nWidth = 400;
        }
        
        // remove current class names, add new ones and set css for starting new animation
        $('#status').removeClass().addClass(nClass).css({
            fontSize : 0
        });
        
        // if a form is to be displayed in the status box and it is currently set to display:none, animate it
        if ($('#status').html().indexOf('<form') !== -1) {
            $('#status form').slideDown();
        }
        
        // begin status box animation
        if ($('#status').css('position') === 'absolute') {
            
            // if position:absolute, the adjust left: position to match new width
            $('#status').animate({
                width : nWidth + 'px',
                marginLeft : '-' + (nWidth / 2) + 'px',
                fontSize : '14px'
            }, 200);
            
        } else {
            
            // if position: is not absolute, don't bother adjusting left position
            $('#status').animate({
                width : nWidth + 'px',
                fontSize : '14px'
            }, 100);
            
        }
    }
    
};


/************************/
// smooth status
/************************/
function swapStatus(status) {
    
    if ($('#status').css('display') === 'none') {
        
        $('#status').html('&nbsp;').slideDown(500, function () {
            $('#status').html(status);
            $('#status *').fadeIn(200);
        });
        
    } else if ($('#status *').html() !== status.replace(/<\S[^>]*>/g, '')) {
        
        $('#status *').fadeOut(200, function () {
            $('#status').html(status);
            $('#status *').fadeIn(200);
        });
        
    }
};


/************************/
// show hidden option lists
/************************/
function showOptions(leftPos) {
    if ($('.options ul').css('display') === 'none') {
        $('.options ul').css('left', leftPos).fadeIn('slow');
    } else {
        $('.options ul').fadeOut('slow');
    }
};


/************************/
// no cache for logged in user
/************************/
function visionNoCache() {
	
	var visionRandStr, visionAllLinks, visionAllForms, visionLinkDomain, visionFormDomain, visionNoCacheEle, i;
	
	visionRandStr = String((new Date()).getTime()).replace(/\D/gi, '').substr(5);
	if (window.location.href.indexOf('vision-nc=') !== -1 || window.location.href.indexOf('/vision/settings') !== -1 || window.location.search.indexOf('mode=') !== -1) {
		
		// get all links
		visionAllLinks = document.getElementsByTagName('a');
		visionAllForms = document.getElementsByTagName('form');
		
		
		// a elements
		for (i = 0; i < visionAllLinks.length; i++) {
			
			// set values to link variables
			visionLinkDomain = visionAllLinks[i].href.replace('http://', ''); // remove http for checking domain
			visionLinkDomain = visionLinkDomain.substr(visionLinkDomain, visionLinkDomain.indexOf('/'));
			
			// continue to next loop??
			if (visionLinkDomain !== window.location.hostname || 
				visionAllLinks[i].href === 'undefined' || 
				visionAllLinks[i].href.indexOf('mailto:') !== -1 || 
				visionAllLinks[i].parentNode.className.indexOf('vision_cms_toolbar') !== -1 || 
				visionAllLinks[i].href.indexOf('vision-nc=') !== -1 || 
				visionAllLinks[i].href.indexOf('#') !== -1) {
				
				continue;
			}
			
			visionAllLinks[i].href += (visionAllLinks[i].href.indexOf('?') !== -1 ? '&' : '?') + 'vision-nc=' + visionRandStr;
			
		}
		
		
		// form elements
		for (i = 0; i < visionAllForms.length; i++) {
			
			if (visionAllForms[i].action.indexOf('http://') === -1) {
				visionAllForms[i].action = 'http://' + window.location.hostname + visionAllForms[i].action;
			}
			
			visionFormDomain = visionAllForms[i].action.replace('http://', ''); // remove http for checking domain
			visionFormDomain = visionFormDomain.substr(visionFormDomain, visionFormDomain.indexOf('/'));
			
			// continue to next loop??
			if (visionFormDomain !== window.location.hostname || 
				visionAllForms[i].action === 'undefined' || 
				visionAllForms[i].action.indexOf('mailto:') !== -1 || 
				visionAllForms[i].action.indexOf('vision-nc=') !== -1 || 
				visionAllForms[i].action.indexOf('#') !== -1) {
				
				continue;
			}
			
			visionNoCacheEle = document.createElement('input');
			visionNoCacheEle.name = 'vision-nc';
			visionNoCacheEle.value = visionRandStr;
			visionNoCacheEle.readOnly = true;
			visionNoCacheEle.style.display = 'none';
			visionAllForms[i].appendChild(visionNoCacheEle);
			
			
		}
		
		
	}
	
};

visionNoCache();


/************************/
// submit comments form
/************************/
$('#comments-form').submit(function () {

    $('#status').html('Adding your comment...').slideDown('slow');
    $('#comment').val(FCKeditorAPI.GetInstance('comment').GetHTML());
    $.ajax({
        url : $('#comments-form').attr('href'), 
        type : 'POST', 
        data : $('#comments-form').serialize(), 
        success : function (status) {
            $('#status').html(status);
        }
    });
    
    return false;
});


/************************/
// open filemanager
/************************/
$('#vision-menu-files').click(function () {
    
    var visionFMWidth, visionFMHeight, visionFMx, visionFMy;
    visionFMWidth = window.innerWidth - 10;
    visionFMHeight = window.innerHeight - 10;
    visionFMx = (screen.width - visionFMWidth) / 2;
    visionFMy = (screen.height - visionFMHeight) / 2;
     
    window.open(this.href, 'fileManager', 'scrollbars=1,status=1,resizable=1,width=' + visionFMWidth + ',height=' + visionFMHeight + ',top=' + visionFMy + ',left=' + visionFMx);
    return false;
    
});



$(function () {
    
	var val, vld, vse, i, hcS; // hcS = headContainerSelector	
	
	// captcha image
    if ($('#abc').length !== 0 && $('#code').length > 0) {
        randImg();
    }
    
    // resize footer on load and onresize
    if ($('#vision-foot').length > 0) {
        footerHeight();
        $(window).resize(function () {
            footerHeight();
        });
    }
	
	
    /******************************/
    // header
    /******************************/
    hcS = '#head-container ';
    
    // add background containers to bookmark lists
    $(hcS + '.bookmarks li:not(:first-child) a').prepend('<img src="/images/vision/blank.gif" width="16" height="16" alt="Social bookmarking icon" />');
    
    // open / close bookmarks
    $(hcS + '.bookmarks li:first-child').click(function () {
        if ($(hcS).css('height').toLowerCase() === '173px') {
            $(hcS).animate({height : '227px'}, 600);
        } else {
            $(hcS).animate({height : '173px'}, 400);
        }
    });
    
    // browser bookmark
    $(hcS + '.bookmarks li:nth-child(2) a').click(function () {
        if (document.all) {
            window.external.AddFavorite(window.location.href, document.title);
        } else {
            alert('To bookmark this page with your browser, press CTRL + D');
        }
        return false;
    });
    
    
    // load / hide search
    $('.additional li:nth-child(2) a').click(function () {
        
        if ($(hcS + ' form').length === 0) {
            $.ajax({
                url : this.href,
                success : function (gsb) {
                    $(hcS).append(gsb);
                    $(hcS + ' form').fadeIn(600);
					visionNoCache();
                }
            });
        } else if ($(hcS + ' form').css('display').toLowerCase() === 'none') {
            $(hcS + ' form').fadeIn(600);
        } else {
            $(hcS + ' form').fadeOut(400);
        }
        
        return false;
        
    });
	
    
    // open brochure in new window
    $(hcS + '.additional li:nth-child(3) a').click(function () {
        window.open(this.href);
        return false;
    });
    
    
    /******************************/
    // body stuff
    /******************************/
    // error 404 page google searc
    if ($('li.search-goog form').length > 0) {
        $('li.search-goog form').attr('action', '/index/search.html').removeAttr('onsubmit');
        $('li.search-goog form').append('<input type="hidden" name="cx" value="009780317067091294708:jxqtkugkxii" /><input type="hidden" name="cof" value="FORID:11" /><input type="hidden" name="ie" value="UTF-8" />');
    }
    
    /******************************/
    // footer
    /******************************/
    // bg for vision powered by
    $('#foot-container .various li:nth-child(7) a').prepend('<img src="/images/vision/blank.gif" width="103" height="37" alt="Powered by Vision" />');
	
	
	/************************/
	// open external links in new window
	/************************/
	val = document.getElementsByTagName('a');
	
	for (i = 0; i < val.length; i++) {
		
		 // check if link goes to an external domain
		vld = val[i].href.replace('http://', '');
		vld = vld.substr(vld, vld.indexOf('/'));
		
		// check if link's domain is external, if so then simulate target=_blank (aslong as it's not spposed to open in colorbox)
		if (vld !== window.location.hostname && vld.length > 0 && val[i].className.indexOf('colorbox') === -1) {
			
			if (val[i].addEventListener) {
				// firefox etc
				val[i].addEventListener('click', function (e) {
					window.open(this.href);
					e.preventDefault();
					e.stopPropagation();
					return false;
				}, false);
				
			} else {
				// ie
				val[i].attachEvent('onclick', function () {
					vse = event.srcElement;
					if (vse.tagName !== 'A') {
						vse = vse.parentNode;
					}
					window.open(vse.href);
					return false;
				});
				
			}
		}
		
	}
	
	
	
	
	
	/**
	 * Homepage scrolling category menu.
	**/
	
	
	
	
	// Get element.
	var element = $('div.index-page + div#foot-container ul.menu.cats');
	
	if (element.length)
	{
		setTimeout
		(
			function ()
			{
				// Get current offset.
				var co = element.offset().top;
				
				// Store the current offset.
				var so = co;
				
				// Is any of the element hidden off the bottom?
				var ep = co + element.outerHeight();
				
				// Get window height + scroll position.
				var wh = $(window).height() + $(window).scrollTop();
				
				// Do we need to move the element?
				if (ep > wh)
				{
					element.css('position', 'absolute').animate
					(
						{
							top : '-' + (ep - wh) + 'px'
						},
						2500,
						function ()
						{
							element.css
							({
								position : 'fixed',
								top : 'auto',
								bottom : 0
							});
							
							
							$(window).bind
							(
								'scroll',
								function (event)
								{
									// Get current offset.
									co = element.offset().top;
									
									// Is any of the element hidden off the bottom?
									ep = co
									
									if (ep >= so)
									{
										$(window).unbind('scroll');
										element.css
										({
											position : 'relative',
											top : 'auto',
											bottom : 'auto'
										});
									}
								}
							);
						}
					);
				}
			},
			2500
		);
	} 
});
