/*
*   Product Selection Tabs & Select All Action (used only on products_suites
*
*   multiple page updates is intended to allow the user surf multiple pages simultaneously.
*   if the user update the cart on page #1 then updates or refreshes page #2, the cart stays in sync
*   This needs to be supported on the server side by passing the current cart items back in a json object
*/

$(function() {
    //Removed by request. Server should be returning page in proper state
    //$('.content-product-container').hide();
    //$('div.expander-addr > div').hide();
	//$('#login-overlay').hide();
	//$('#select-and-connect-overlay').hide();

	//Turn 'on' the folder icon when clicked.  Product class '.product-indicator' is currently the folder icon.
    //use live instead of click() or bind() so functionality is available to newly created elements
	$('a.product-indicator, a.product-removal').live('click',function () {
		var that = this;
		var href = this.href.substr(0,this.href.indexOf('/ru')) + '/ru/ajax'; //modify embedded to url for ajax
		$.getJSON(href, function(data){
			$('#selected-products-cart').empty(); //remove all items in cart
			//data.cart is an array of products, (eg data.cart[2].id)
			$.each(data.cart, function (){
				$('a.product-indicator[rel='+this.id+']')
				    .removeClass('alt')                     //set item to default state 'alt'
				    .addClass((castStringToBoolean(this.selected))?'alt':'')   //CK: added castStringToBool, if selected then add class='alt'
				    .attr('href', this.action);
				//if (this.selected) $('#selected-products-cart').append(buildCartListItem(this));
				if (castStringToBoolean(this.selected)) $('#selected-products-cart').append(buildCartListItem(this));
			});
            updateCartDisplay(); //show hide appropriate containers in "1. Select" box
			updateAddAllButton(data.suite);

 		});
		return false;
	});

    //use live events since these elements are added and remove continuously
    //target show/hide details link for click since addressing doesn't support live events
    //scroll opened item into view
    $('a.selected-product').live('click',function (){
        //if the link points to a product on this page then open expander and cancel default link action
        //else the link must go to a product in another suite so let the link proceed normally
        if ($('.link-showdetails[rel='+$(this).attr('rel')+']').length) {
            var el = $('.link-showdetails[rel='+$(this).attr('rel')+']').click();
            var targetOffset = el.parents('.product-intro').offset().top;
            $('html,body').animate({scrollTop: targetOffset}, 500); //scroll open expander into view
            return false;
        }
    });

// 	$('.selected-remove').hover(function() {
//		$(this).addClass('selected-remove-hover');
//	}, function() {
//		$(this).removeClass('selected-remove-hover');
//	});

    /*
     * Recreates the hover state for folder rollover text for down level browsers.
     * if the product-indicator is in 'alt' state then show the remove from folder text
     * and hide the add to folder text
     */
	$('.products-list a.product-indicator').hover(function() {
		$(this).addClass('hoverstate');
		//if class is alt then product is already in folder, so show the remove from folder text
		//use visiblity:hidden instead of display:none for screen readers
 		//commented out for connect form changes
		//if ($(this).hasClass('alt')) {
 		//	$(this).children('.add').hide();
 		//	$(this).children('.remove').css({"visibility":"visible","display":"inline"});
 		//} else {
 		//	$(this).children('.remove').hide();
 		//	$(this).children('.add').css({"visibility":"visible","display":"inline"});
 		//}
	}, function() {
		$(this).removeClass('hoverstate');
		//if ($(this).hasClass('alt')) {
		//	$(this).children('.add').hide();
		//	$(this).children('.remove').css({"visibility":"hidden","display":"inline"});
		//} else {
		//	$(this).children('.remove').hide();
		//	$(this).children('.add').css({"visibility":"hidden","display":"inline"});
		//}
	});

	$('.login-overlay-close').click(function() {
		$.unblockUI();
		return false;
	});

    //on click, check if user is logged in,
    //if user is logged in then submit form via ajax and  update display on response
    //if user is not logged in then show login overlay
    $('#selected-products-save, #account-connect-save').click(function() {
    //Removed check for login. Client will handle login check on server side
        if (isLoggedIn()) {
            $.ajax({
                url: '/products-folder/save/ru/ajax?savedcarts='+$('#savedcarts').val(), 
                type: $(this).parents('form').attr('method'),
                dataType: 'json',
                beforeSend: function (){
                    $('#selected-products-save a').addClass('progress');
                },
                success: function (data){
                    updateDisplayOnSuccess(data);
                },
                complete: function (){
                    $('#selected-products-save a').removeClass('progress');
                    orangeBoxTooBig();
                },
                //error: moved to $("#error-overlay").ajaxError [see below]
				error: function (xhr, opt){  //server error (eg timeout function)
					//xhr.handled = true;
					return true;
				}	//CK: removed extra comma
            });
            return false;
        }
    });

    //error handler to catch all ajax errors and show a generic message
    $("#error-overlay").ajaxError(function(evt, xhr, opt){
        if (xhr.handled) return; //if the error has already been caught and handled then just return
        $('#error-message h1').text(xhr.status + ' ' + xhr.statusText);
        $('#error-message p').text(xhr.getResponseHeader('Warning'));

        $.blockUI({
            css: {
                height: '200px',
                width: '400px',
                margin: '0 auto',
                cursor:'default',
                border: '1px solid black'
            },
            overlayCSS: {
                cursor:'default',
                opacity: '0.8'
            },
            message: $('#error-overlay')
        });
    }).find('#close-error-overlay').click(function (){
		$.unblockUI();
		return false;
    });

    //Stub fn: this needs to be implemented by client depending on the server process
    $('#savedcarts').change(function (){
        //alert('reload page with cart #' + $(this).val());
        
    	var s = document.getElementById("savedcarts");
		if(s.selectedIndex == 0){
			return false;
		}
		var x=document.getElementById("save-cart-form")
		var _src = x.action;
		_src = _src.replace('/save/','/view/');
		//x.action="/products-folder/view/ru/products/merchants/paycard-and-reloadable-debit-cards";
		x.action = _src;
		x.submit();
		orangeBoxTooBig();
		return true;
    });
});

//first href points to actual page and rel is the product id
//second href points to server page to maintain session
//  <li>
//      <a href="product_3.html" class="selected-product" rel="3"><span class="move_">Remove</span>Fuel Cards (Transportation Services)</a>
// 	    <a href="_data/products_suite_update.js?product=3" class="product-removal alt"><span class="selected-remove"><span class="move_">Remove selection</span></span></a>
//  </li>
function buildCartListItem(item) {
    return '<li>'+
                '<a href="'+item.url+'" class="selected-product" rel="'+item.id+'"><span class="move_">Remove<\/span>'+item.text+'<\/a>'+
		        '<a href="'+item.action+'" class="product-removal alt"><span class="selected-remove"><span class="move_">Remove selection<\/span><\/span><\/a>'+
		   '<\/li>';
}

//if all the products in the suite are in the cart (eg. class="product-indicator alt") then change the add-all button
function updateAddAllButton(suite) {
    $('span.add-all').text(suite.text);
    if (castStringToBoolean(suite.selected)) {
        $('.products-header a.product-indicator').addClass('alt').attr('href',suite.action);
    } else {
        $('.products-header a.product-indicator').removeClass('alt').attr('href',suite.action);
    }
}

function updateCartDisplay() {
    var savedFolder = ($('#savedcarts').length > 0 && !($('#savedcarts').is(':empty')))?true:false;
    var cart = $('#selected-products-cart').children();
   
    if (cart.length) {
		$('#connect-form-button-cs').hide();
        $('#selected-products-cart, #selected-products-print, #selected-products-save, #connect-form-button-sts').fadeIn();
    }else{
    	$('#connect-form-button-cs').fadeIn();
		$('#selected-products-cart, #selected-products-print, #selected-products-save, #connect-form-button-sts').hide();
    } 
    
    if ((!isLoggedIn() && !cart.length) || (isLoggedIn() && !savedFolder && !cart.length)) {
        $('#instructions-A').fadeIn();
        $('#instructions-B').hide();
    } else if (!isLoggedIn() && !savedFolder && cart.length) {
        $('#instructions-A, #instructions-B, #selected-products-dropdown').hide();
    } else if (isLoggedIn() && savedFolder && !cart.length) {
        $('#instructions-B, #selected-products-dropdown,').fadeIn();
        $('#instructions-A').hide();
    } else if (isLoggedIn() && cart.length) {
        if (!$('#savedcarts').children().length) {
            $('#savedcarts').append('<option value="default">New Folder</option>').selectbox();
        }
        $('#selected-products-dropdown').fadeIn();
        $('#instructions-A, #instructions-B').hide();
    }
    //CK: Added fallback state
    /*
    else {
     	$('#selected-products-cart, #selected-products-dropdown, #selected-products-print, #selected-products-save').fadeIn();
		$('#instructions-A, #instructions-B').hide();
     }
     */
}

function updateDisplayOnSuccess(data){
	if($('#savedcarts').val() != data.cart.id){
		$('#savedcarts').append('<option value="'+data.cart.id+'" selected="selected">'+data.cart.name+'</option>').selectbox();
	}
	
    $('#selected-products-save').data('origText', $('#selected-products-save').val()).val(data.cart.name);
    setTimeout(function (){
        $('#selected-products-save').val($('#selected-products-save').data('origText'));
    }, 5000);
    updateCartDisplay();
}

//Workaround: The server set the JSON values as string instead of primitives so
//convert string to boolean to get intended results
function castStringToBoolean(str) {

    if (typeof str === 'boolean')
        return str;    //if incoming str is boolean then return.
    else
        return (str.toLowerCase() === 'true')?true:false; //else cast string 'true|TRUE|True' to boolean true


}

//Check cookie if user is logged in
function isLoggedIn(){
    var state = (readCookie('loggedIn').toLowerCase() == 'true')?true:false;
    return state;
}

//courtesy of Quirks Mode
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return '';
}

//Just for dev/tsting (keep for reference)_
// function createCookie(name,value,days) {
// 	if (days) {
// 		var date = new Date();
// 		date.setTime(date.getTime()+(days*24*60*60*1000));
// 		var expires = "; expires="+date.toGMTString();
// 	}
// 	else var expires = "";
// 	document.cookie = name+"="+value+expires+"; path=/";
// }
//
// createCookie('loggedIn','true');
