var GB_ROOT_DIR = "/webresources/scripts/greybox/";
//window.onload = init;

$(document).ready(function(){
	highlightSearch(); 		
	showFlyout();
	showBrands();
});


function init()
{
	if (getCookie("tabs") == null || getCookie("tabs") == "prods") dispProds();
	else dispMans();
	
	if (getCookie("shipping") == null)
	{
		if (document.getElementById('addressform') != null) document.getElementById('addressform').style.display="block";
		if (document.getElementById('address-select') != null) document.getElementById('address-select').style.display="none";
		if (document.getElementById('shippy') != null) document.getElementById('shippy').style.display="none";
	}
	else
	{
		if (document.getElementById('addressform') != null) document.getElementById('addressform').style.display="none";
	}
	
	toggleHistory();
}

function dispProds()
{
	if (document.getElementById('prods') != null)
	{
		document.getElementById('prods').style.display="block";
		document.getElementById('mans').style.display="none";
		document.getElementById('prodheader').className="on";
		document.getElementById('manheader').className="";
		setCookie("tabs", "prods", "", "/", "", "");
	}
}

function dispMans()
{
	if (document.getElementById('prods') != null)
	{
		document.getElementById('mans').style.display="block";
		document.getElementById('prods').style.display="none";
		document.getElementById('manheader').className="on";
		document.getElementById('prodheader').className="";
		setCookie("tabs", "mans", "", "/", "", "");
	}
}


function dispCC()
{
	document.getElementById('ccblock').style.display="block";
    var poBlock = document.getElementById('poblock');
    if(poBlock){
        poBlock.style.display="none";
    }
	
}

function dispPO()
{
	document.getElementById('poblock').style.display="block";
	document.getElementById('ccblock').style.display="none";
}



	function showElement(id, sender) {
		if(document.getElementById) {
			var element = document.getElementById(id);
			
			if(element) {
				element.style.display = 'block';
			}
			
			if(sender) {
				sender.style.display = 'none';
			}
		}		
	}
	
	function hideElement(id, sender) {
		if(document.getElementById) {
			var element = document.getElementById(id);
			
			if(element) {
				element.style.display = 'none';
			}			
		}		
	}
	
	function toggleElement(id, sender) {
		if(document.getElementById) {
			var element = document.getElementById(id);
			
			if(element) {
				if(element.isOn) {
					element.style.display = 'none';
					element.isOn = false;
				} else {
					element.style.display = 'block';
					element.isOn = true;
				}				
			}
			
			if(sender) {
				sender.style.display = 'none';
			}
		}		
	}


/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}


/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}


/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function toggleHistory()
{
	if (document.getElementById('history'))
	{
		if (document.getElementById('history').style.display=="none")
		{
			document.getElementById('history').style.display="block";
		} else {
			document.getElementById('history').style.display="none";
		}
	}	
}

function distributeTasks(){
	var links = document.getElementsByTagName("a");
	for(var i=0; i<links.length; i++){
		links[i].onclick = function(){
			if(this.className == "print"){
				window.print();	
				return false;
			}
			else if(this.className == "email"){
				var location = window.location;
				var title = this.title;
				location.href = "mailto:?subject="+title+"&body="+escape(location.href);
				return false;	
			}
			
		}
	}
}

function highlightSearch(){
	
	$('#Template_Content_Search, .search .medium').click(function(){			
		var str = $(this).attr('value');
		if(str == $(this).attr('title')){
			$(this).attr({value: ""});
			$(this).select();
		}
	});
	$('#Template_Content_Search').blur(function(){			
		var str  = $(this).attr('value');
		if((str == "") || (str == undefined)){
			$(this).attr({value:'Search'});
		}	
	});	
}

function showFlyout(){
	$('#expandable').click(function(){
		$('#flyout').slideToggle('slow');	
		return false;
	});
	$('#flyout .close').click(function(){
		$('#flyout').slideToggle('slow');
		return false;
	});
}

function showBrands(){
	$('.manufacturerList td').each(function(){
		var elems = $('li',this);
		if(elems.length <= 1){
			var viewbrands = $('.viewbrands', this);
			var close = $('.close', this);
			viewbrands.css('visibility', 'hidden');
			close.css('visibility', 'hidden');
		}
	});
	$('.viewbrands').click(function(){
		var parent = $(this).parent('.manufacturer_column');
		var list = $(parent).children('ul');
		$('.manufacturerList .image img').fadeTo('fast',0.1);
		$('.viewbrands').css('visibility','hidden');
		$(list).slideToggle('fast');	
		return false;
	});
	
	
	$('.manufacturerList ul .close').click(function(){
		var parent = $(this).parent().parent().parent();
		var list = $(parent).children('ul');
		$(list).slideToggle('fast');	
		$('.manufacturerList .image img').fadeTo('fast',1);
		$('.viewbrands').css('visibility','visible');
		
		$('.manufacturerList td').each(function(){
		var elems = $('li',this);
		if(elems.length <= 1){
			var viewbrands = $('.viewbrands', this);
			var close = $('.close', this);
			viewbrands.css('visibility', 'hidden');
			close.css('visibility', 'hidden');
		}
	});
		
		return false;
	});
}

var newsletter = {  
    init: function() {
        newsletter.newsletterSignupPopup();
        newsletter.showNewsletterSignupPopup();
        newsletter.hideNewsletterSignupPopup();
    },
       
    newsletterSignupPopup: function(){
        $('#newsletterSignup').dialog({
          title: 'Sign-up for the KR Anderson Newsletter',
          width: 525,
          height: 300,
          bgiframe: true,
          modal: true,
          autoOpen: false,
          closeOnEscape: true,
          overlay: {
            backgroundColor: '#000000',
            opacity: 0.5
          }
        });
    },

    showNewsletterSignupPopup: function(){
        $('#newsletterSignupPopup').click(function(){
            $('#newsletterSignup').dialog('open');   
            $('#saveNewsLetter').click(function() {
                newsletter.saveNewsLetter();
            });     
            // need to attach back to the form for the .net buttons to work
            $('#newsletterSignup').parent().appendTo($("form:first"));
        });
    },
    
    hideNewsletterSignupPopup: function(){
        $('#cancelNewsLetter').click(function(){
          $('#newsletterSignup').dialog('close');
        });
    },
    
    saveNewsLetter: function() {
        var fullName = $('#newsLetterFullName').val();
        var email = $('#newsLetterEmail').val();
        
        $.ajax({
            type: "POST",
            url: "/services/kra.asmx/Subscribe",
            data: "{'fullName':'" + fullName + "', 'email':'" + email + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function() {
                $('#loader').removeClass('hidden');
            },
            success: function(result) {
                if(result == 'Success') {                    
                    newsletter.showPanel('nsinformation', 'Thank you for signing up for our newsletter.')
                } else {                    
                    newsletter.showPanel('nserror', result)
                }
            },
            error: function(xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                alert(err.Message)
            }
        });
    },
    
    saveNewsLetterOnHomePageSignUp: function() {
        
        var email = $('#newsLetterEmail1').val();
        var fullName = '';
                
        $.ajax({
            type: "POST",
            url: "/services/kra.asmx/Subscribe",
            data: "{'fullName':'" + fullName + "', 'email':'" + email + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function() {
                //$('#loader').removeClass('hidden');
            },
            success: function(result) {
                
                if(result == 'Success') {
                    newsletter.showPanel('nsinformation', 'Thank you for signing up for our newsletter.')
                    newsletter.hideHomePageSignup();                   
                    
                } else {
                    alert(result);
                    //newsletter.newsletterSignupPopup();
                    //newsletter.showNewsletterSignupPopup();
                    //newsletter.hideNewsletterSignupPopup();
                    //newsletter.showPanel('nserror', result)
                }
            },
            error: function(xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                alert(err.Message)
            }
        });
    },
    
    clearPanels: function() {
        $('#nsinformation li').remove();
        $('#nserror li').remove();
        $('#nsinformation').addClass('hidden');
        $('#nserror').addClass('hidden');
    },

    showPanel: function(type, message) {
        newsletter.clearPanels();
        $('#' + type).append('<li>' + message + '</li>');
        $('#' + type).removeClass('hidden');
        //$('#' + type).get(0).scrollIntoView(true);
		
		$(function() {
			// setTimeout() function will be fired after page is loaded
			// it will wait for 5 sec. and then will fire
			// $("#successMessage").hide() function
			setTimeout(function() {
				$("#nsinformation").hide("slow")
				$('#newsletterdiv').show();
			}, 5000);
		});

    }
}