var validEmail = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;

var statsoft = function(){
    function setupSlider(selector) {
    	
    	var parent = $(selector),
    		container = parent.find('.scroll .container'),
    		panels = parent.find('.scroll .container > li');

    	var horizontal = true;

    	if (horizontal) {
    	  panels.css({
    	    'float' : 'left',
    	    'position' : 'relative'
    	  });
    	  
    	  container.css('width', panels[0].offsetWidth * panels.length);
    	}

    	var scroll = parent.find('.scroll').css('overflow', 'hidden');

    	function selectNav() {
    	  $(this)
    	    .parents('ul:first')
    	      .find('a')
    	        .removeClass('selected')
    	      .end()
    	    .end()
    	    .addClass('selected');
    	}

    	parent.find('.navigation a').click(selectNav);
    	
    	function trigger(data) {
    	  var el =  parent.find('.navigation a[href$="' + data.id + '"]').get(0);
    	  selectNav.call(el);
    	}

    	if (window.location.hash) {
    	  trigger({ id : window.location.hash.substr(1) });
    	} else {
    	  $('ul.navigation a:first').click();
    	}
    	
    	var offset = parseInt((horizontal ? 
    	  container.css('paddingTop') : 
    	  container.css('paddingLeft')) 
    	  || 0) * -1;


    	var scrollOptions = {
    	  target: scroll,
    	  items: panels,
    	  navigation: '.navigation a',
    	  axis: 'xy',
    	  onAfter: trigger, 
    	  offset: offset,
    	  duration: 500,
    	  easing: 'easeInOutSine'
    	};
    	
    	parent.serialScroll(scrollOptions);
    	
    	$.localScroll(scrollOptions);
    	
    	scrollOptions.duration = 1;
    	$.localScroll.hash(scrollOptions);
    }
    
    function giveRadioToggleFieldset(yesRadio, noRadio, fieldset) {
        var functions = {
            yesChangeHandler: function() {
                $(fieldset).show();
                $(fieldset).find('input').attr('disabled', '');
                
            },
            noChangeHandler: function() {
                $(fieldset).hide();
                $(fieldset).find('input').attr('disabled', 'disabled');
            }
        };
        
        yesRadio.change(functions.yesChangeHandler);
        noRadio.change(functions.noChangeHandler);
    }
    
    function requestXmlData(url, callback) {
        var requestOptions = {
            dataType: 'xml',
            url: url,
            success: callback
        };
        
        $.ajax(requestOptions);
    }
    
    function resetSelectOptions(selects, removeNoneDefault) {
        removeNoneDefault = removeNoneDefault || false;
        if(removeNoneDefault)
        {
          $(selects).find('option[class!="default"]').remove();
        }
        
        $(selects).find('option.default').first().attr('selected', 'selected');
    }
    
    function setupOrderForm(selector) {
    
    	var form = $(selector)
    	    table = form.find('fieldset.products table'),
    	    price = form.find('ul.price').first(),
    	    newButton = table.find('button.new').first(),
    	    quantitySelectors = table.find('tbody tr select.quantity'),
    	    productSelectors = table.find('tbody tr select.product'),
    	    productData = null;
    	
    	giveRadioToggleFieldset(
    	    form.find('#order_fakturering_separat_adress_yes'), 
    	    form.find('#order_fakturering_separat_adress_nej'), 
    	    form.find('#order_fakturering')
    	);
    	
    	var functions = {
    		updateRowPrice: function(row) {
    			var quantity = $(row).find('select.quantity').val(),
    				product = $(row).find('select.product').val(),
    				productPrice = functions.getValueForProduct(product, 'price'),
    				priceElement = $(row).find('td.sub span.sum').first(),
    				totalElement = $(row).find('td.total span.sum').first(),
    				total = productPrice * quantity;
    			
    			priceElement.text(productPrice);
    			totalElement.text(total);
    			
    			functions.updateTotalPrice();
    		},
    		getValueForProduct: function(product, attribute) {
    		    var product = $(productData).find('item:contains('+product+')').first();
                return product.length && $(product).attr(attribute) != undefined  ? parseInt($(product).attr(attribute)) : 0;
    		},
    		updateTotalPrice: function() {
    			var rows = table.find('tbody tr'),
    			    priceSum = 0,
    			    vatSum = 0,
    			    rowPrice,
    			    rowVat,
    			    rowDiscount,
    			    product,
    			    shippingSum = 0,
    			    discountSum = 0;
    			
    			$(rows).each(function(index, element) {
    			    product = $(element).find('select.product').first().val();
    			    quantity = $(element).find('select.quantity').first().val();
    			    rowVat = functions.getValueForProduct(product, 'vat');
    			    rowPrice = functions.getValueForProduct(product, 'price');
    			    rowDiscount = functions.getValueForProduct(product, 'discount');
    			    priceSum += rowPrice * quantity;
    			    discountSum += rowDiscount * quantity;
    			    vatSum += parseInt((rowVat / 100) * (rowPrice - rowDiscount)) * quantity;
    			});  			
    			
    		    var vatElement = price.find('span.vat.sum').first(),
    			    totalElement = price.find('span.total.sum').first()
    			    subElement = price.find('span.sub.sum').first(),
    			    shippingElement = price.find('span.shipping.sum').first(),
    			    discountElement = price.find('span.discount.sum').first();
    		    
    		    discountSum > 0 ? $(discountElement).parents('li.discount').show() : discountElement.parents('li').first().hide();
    		    
    		    shippingSum = parseInt(shippingElement.text());
    		    vatSum += (shippingSum * 1.25) - shippingSum;
    		    
    		    discountElement.text(discountSum);
    			subElement.text(priceSum);
    			vatElement.text(vatSum);
    			totalElement.text(priceSum + vatSum + shippingSum - discountSum);
    		},
    		updateRowNameCounts: function() {
    			var rows = table.find('tbody tr'),
    				count = 1,
    				quantitySelector,
    				productSelector,
    				newQuantityName,
    				newProductName,
    				regexp = /\[(\d+)\]/gi;
    			
    			$(rows).each(function(index, element) {
    				quantitySelector = $(element).find('select.quantity').first();
    				productSelector = $(element).find('select.product').first();
    				
    				newQuantityName = quantitySelector.attr('name').replace(regexp, '['+String(count)+']');
    				newProductName = productSelector.attr('name').replace(regexp, '['+String(count)+']');
    				
    				quantitySelector.attr('name', newQuantityName);
    				productSelector.attr('name', newProductName);
    				
    				count++;
    			});
    		},
    		populateSelectOptions: function(select, groups) {
    		    groups.each(function(index, item) {
    		        var group = $('<optgroup></optgroup>').attr('label', $(item).attr('title')),
    		            option;
    		        
    		        $(item).find('item').each(function(index, item) {
    		           option = $('<option></option>').text($(item).text());
    		           $(group).append(option);
    		        });
    		        
    		        $(select).append(group);
    		    });
    		}
    	};
    	
    	var handlers = {
    		newButtonHandler: function() {
    			var lastRow = table.find('tbody > tr').last(),
    		    	newRow = lastRow.clone(true);
    			
    			resetSelectOptions($(newRow).find('select'));
    			
    			lastRow.after(newRow);
    			functions.updateRowPrice(newRow);
    			functions.updateRowNameCounts();
    			return false;
    		},
    		selectProductHandler: function() {
    			var row = $(this).parents('tr').first();
    			functions.updateRowPrice(row);
    		},
    		selectQuantityHandler: function() {
    			var value = $(this).val(),
    				row = $(this).parents('tr').first();
    			
    			if(value == 0 && table.find('tbody > tr').length > 1)
    			{
    				row.remove();
    				functions.updateTotalPrice();
    				functions.updateRowNameCounts();
    			}
    			else
    			{
    				functions.updateRowPrice(row);
    			}
    		},
    		fetchDataSuccess: function(data, status, request) {
                var groups = $(data).find('group');
                productData = data;
                functions.populateSelectOptions(productSelectors.first(), groups);
            }
    	};
    	
    	newButton.click(handlers.newButtonHandler);
    	quantitySelectors.change(handlers.selectQuantityHandler);
    	productSelectors.change(handlers.selectProductHandler);
    	
    	requestXmlData('/data/products.xml', handlers.fetchDataSuccess);
    }
    
    function setupPager(selector) {
    	var menu = $(selector).find('ul.pager a'),
    	    pages = $(selector).find('div.page');
    	
    	pages.css('display', 'none');
    	
    	var functions = {
    		menuClickHandler: function() {
    			var newSelected = this,
    				newHref = $(newSelected).attr('href'),
    				newPage = $(selector).find(newHref),
    				oldSelected = $(selector).find('ul.pager a.selected'),
    				oldHref = $(oldSelected.first()).attr('href'),
    				oldPage = $(selector).find(oldHref);
    			
    			$(newSelected).addClass('selected');
    			$(oldSelected).removeClass('selected');
    			
    			newPage.css('display', 'block');
    			oldPage.css('display', 'none');
    			
    			return false;
    		},
    		selectedClickHandler: function() {
    			return false;
    		}
    	};
    	
    	menu.click(functions.menuClickHandler);
    }
    
    function setupKursForm(selector) {
    	var	form = $(selector),
    		firstCourseSelect = form.find('tbody select.course'),
    		firstLocationSelect = form.find('tbody select.location'),
    		firstDateSelect = form.find('tbody select.date'),
    		courseData;
    	
    	giveRadioToggleFieldset(
            form.find('#kurs_fakturering_separat_adress_yes'), 
            form.find('#kurs_fakturering_separat_adress_nej'), 
            form.find('#kurs_fakturering')
        );
    	
    	var functions = {
    	    populateCourseSelect: function(select, courses) {
    	        courses.each(function(index, element) {
    	            functions.appendOption(select, $(element).text(), $(element).attr('short'));
    	        });
    	    },
    	    populateLocationSelect: function(select, locations) {
    	        var availableLocations = [];
    	        locations.each(function(index, element) {
    	            var location = $(element).attr('location'),
    	                start = $(element).attr('start'),
    	                end = $(element).attr('end'),
    	                text = start+" — "+end+" | "+location;   
    	            
    	            functions.appendOption(select, text, text);
    	        });
    	        
    	        $(availableLocations).each(function(index, element) {
    	            functions.appendOption(select, element, element);
    	        });
    	    },
    	    populatePrice: function(row, price) {
    	        var sum = $(row).find('td.price span.sum');
    	        
    	        if(price != undefined)
    	        {
    	            sum.text(price);
    	        }
    	        else
    	        {
    	            sum.text(0);
    	        }
    	        
    	        functions.refreshTotalPrice();
    	    },
    	    initCourseSelect: function(select) {
    	        select.change(handlers.courseSelectChange);
    	    },
    	    initLocationSelect: function(select) {
    	        select.change(handlers.locationSelectChange);
    	    },
    	    refreshTotalPrice: function() {
    	        var rowPrices = $(form).find('tbody td.price span.sum'),
    	            subPriceE = $(form).find('ul.price span.sum.sub').first(),
    	            vatPriceE = $(form).find('ul.price span.sum.vat').first(),
    	            discountPriceE = $(form).find('ul.price span.sum.discount').first(),
    	            totalPriceE = $(form).find('ul.price span.sum.total').first(),
    	            subPrice = 0,
    	            vatPrice = 0,
    	            totalPrice = 0,
    	            discountPrices = 0,
    	            discountPrice;
    	        
    	        rowPrices.each(function(index, element) {
    	            var price = parseInt($(element).text());
    	            subPrice += price;
    	            if(price > 0)
    	            {
    	                discountPrices++;
    	            }
    	        });
    	        
    	        switch(discountPrices)
    	        {
    	            default:
    	              discountPrice = 0;
    	            break;
    	            case 2:
    	              discountPrice = 3900;
    	            break;
    	            case 3:
    	              discountPrice = 8800;
    	            break;
    	        }
    	        
    	        vatPrice = Math.round((subPrice - discountPrice) * 1.25 - (subPrice - discountPrice));
    	        totalPrice = vatPrice + subPrice - discountPrice;
    	        
    	        subPriceE.text(subPrice);
    	        vatPriceE.text(vatPrice);
    	        discountPriceE.text(discountPrice);
    	        totalPriceE.text(totalPrice);
    	    },
    	    selectGetParent: function(select) {
    	        return $(select).parents('tr').first();
    	    },
    	    appendOption: function(target, text, value) {
    	        var element = $('<option></option>').text(text).attr('value', value);
                $(target).append(element);
                return element;
    	    },
    	    updateRowNameCounts: function() {
                var rows = $(form).find('tbody tr'),
                    count = 1,
                    courseSelector,
                    locationSelector,
                    newCourseName,
                    newLocationName,
                    regexp = /\[(\d+)\]/gi;
                
                $(rows).each(function(index, element) {
                    courseSelector = $(element).find('select.course').first();
                    locationSelector = $(element).find('select.location').first();
                    
                    newCourseName = courseSelector.attr('name').replace(regexp, '['+String(count)+']');
                    newLocationName = locationSelector.attr('name').replace(regexp, '['+String(count)+']');
                    
                    courseSelector.attr('name', newCourseName);
                    locationSelector.attr('name', newLocationName);
                    
                    count++;
                });
            }
    	};
    	
    	var handlers = {
    	    newButtonHandler: function() {
                var lastRow = $(form).find('tbody > tr').last(),
                    newRow = lastRow.clone(true);
                
                resetSelectOptions($(newRow).find('select.location'), true);
                
                lastRow.after(newRow);
                functions.populatePrice(newRow, 0);
                functions.updateRowNameCounts();
                
                if($(form).find('tbody tr').length >= 3)
                {
                    $(this).parents('tfoot').hide();
                    $(this).hide();
                }
                
                return false;
            },
			fetchDataSuccess: function(data, status, request) {
			    var courses = $(data).find('courses item');
			    
			    courseData = data;
                functions.populateCourseSelect(firstCourseSelect, courses);
                functions.initCourseSelect(firstCourseSelect);
                functions.initLocationSelect(firstLocationSelect);
            },
            courseSelectChange: function() {
                var parent = functions.selectGetParent(this),
                    course = $(this).val(),
                    locationSelect = parent.find('select.location').first(),
                    dateSelect = parent.find('select.date').first(),
                    price  = $(courseData).find('courses item[short="'+course+'"]').attr('price'),
                    rowLength = $(form).find('tbody tr').length;
                
                if(course == 'Välj kurs' && rowLength > 1)
                {
                    if(rowLength <= 3)
                    {
                        $(form).find('tfoot, tfoot tr button').show();
                    }
                    
                    parent.remove();
                    functions.updateRowNameCounts();
                    functions.refreshTotalPrice();
                }
                
                resetSelectOptions(locationSelect, true);
                functions.populatePrice(parent, price);
                functions.populateLocationSelect(locationSelect, $(courseData).find('schedule location[course="'+course+'"]'));
            },
            locationSelectChange: function() {
                var parent = functions.selectGetParent(this);
            }
    	};
    	
    	$(form).find('tfoot button.new').click(handlers.newButtonHandler);
    	
    	requestXmlData('/data/courses.xml', handlers.fetchDataSuccess);
    }
    
    function setupColorbox(selector) {
    	var options = {
    	        slideshow: false,
    	        opacity: 0.65,
    	        rel: 'nofollow',
    	        scrolling: false,
    	        width: 600
    	};
    	
    	$(selector).colorbox(options);
    }
    
    function setupUsers(selector) {
        
        var item = $(selector).find('span.item'),
            rate = 3000,
            users;
        
        var methods = {
            fetchDataSuccess: function(data, status, request) {
                users = $(data).find('user');
                setInterval(methods.changeUser, rate);
                $(selector).show();
            },
            changeUser: function() {
                var current = $(item).text(),
                    user = null,
                    currentIndex = 0
                    nextIndex = 0;
                
                $(users).filter(function(index) { 
                    if($(this).text() == current) currentIndex = index;
                });
                
                nextIndex = currentIndex + 1 != users.length ? currentIndex + 1 : 0;
                
                user = users[nextIndex];
                
                $(item).fadeOut(Math.round(rate / 8), function() {
                    $(this).text($(user).text());
                    $(this).fadeIn(Math.round(rate / 8));
                });
            }
        };
        
        
        requestXmlData('/data/users.xml', methods.fetchDataSuccess);
    }
	
	  function setupNewsletterValidator(form) {
	    var $form = $(form);
	    
	    function submitHandler() {
	      var email = $(this).find('input'),
	          value = $(email).attr('value');
	      if(!value || value.trim() === '' || value === email.attr('title') || !validEmail.test(value))
	      {
	        alert('Du måste fylla i din e-postadress');
	        return false;
	      }
	    };
	    
	    $form.submit(submitHandler);
	  }
	  
	  function setupFauxLabel(elements) {
      elements = $(elements);
      
      function focus() {
        var self = $(this);
        if(self.val() == self.attr('title')) self.val('').addClass('editing');
      };
      
      function blur() {
        var self = $(this);
        if(self.val() == '') self.val(self.attr('title')).removeClass('editing');
      };
      
      elements.blur(blur).blur();
      elements.focus(focus);
    };
	
	function getResources() {
    	return {
    		'#slider': setupSlider,
    		'#order': setupOrderForm,
    		'#kurs': setupKursForm,
    		'#pager': setupPager,
    		'a[rel="window"], a.window': setupColorbox,
    		'#statistica-users': setupUsers,
    		'form#newsletter': setupNewsletterValidator,
    		'.faux-label': setupFauxLabel
    	};
    }

	return {
      init: function(){
         var resources = getResources(),
         	 selector,
         	 elements,
         	 callback; 
         
		 for(selector in resources) {
			 elements = $(selector);
			 callback = resources[selector];
			 
			 if(elements.length) callback(selector);
		 }
      }
    }
}();

$(document).ready(statsoft.init);

