/**
 * @author neila
 */
$(function() {
	if(!$.support.cssFloat) {
		var zIndexNumber = 1000;
		$('#header,#content').each(function() {
			$(this).css('zIndex', zIndexNumber);
			zIndexNumber -= 10;
		});
	}
});

$(document).ready(function(){
	
   $('body').addClass('js_enabled');
    
	DD_roundies.addRule('div.landing_product,#adoption_landing #pack_contents',"6px",true);
	DD_roundies.addRule('#checkout_steps div,#b_get_address.submit,#r_get_address.submit,#cc_get_address',"2px",true);
	DD_roundies.addRule('#wwf_home_link',"0px 0px 2px 2px",true);
	DD_roundies.addRule('p.shop_button input,p.shop_button a',"2px",true);
	DD_roundies.addRule('#checkout_holder,#confirmation_holder,#login_holder,#account_holder,#login_holder,#cert_instructions,#pack_contents',"0px 0px 6px 6px",true);
	DD_roundies.addRule('#child_options.donation',"0px 0px 6px 6px",true);
	
	/* IE6 Transparancies */
    if (browser_is_ie6()) {
		$('#header').supersleight();
		$('#content').supersleight({backgrounds:false});
		$('#basket_upsell_header').supersleight();
		
//		$('.item_holder,.main_product,.product_holder,.cart_item,ul.ticked li').supersleight();
    }
    
    /* Search box */
    $('#search_query').focus(function(){
        if ($(this).val() == 'Search our Shop') 
            $(this).val('');
    });
    $('#search_query').blur(function(){
        if ($(this).val() == '') 
            $(this).val('Search our Shop');
    });
    
    /* Footer links shade layer handler */
    $('li.footer_link a.content').bind('click keyup', function(e){
    
        e.preventDefault();
        
        content_id = $(this).attr('class').split(' ').pop();
        link_ref = '?page=content&amp;id=' + content_id;
        
        shade_layer('content', '744', '496', 'B3B7BD', link_ref, '', '');
    });
    
    /* PAF lookup */
    $('.paf_action').click(function(e){
    
        e.preventDefault();
        
        var this_prefix = $(this).attr('id').substr(0, $(this).attr('id').indexOf('_'));
        var fieldset = $(this).parents('fieldset:first');
        var postcode = fieldset.find('input.postcode_lookup').val();
        var house_name = fieldset.find('input.house_name').val();
        
        if (!postcode || !house_name) {4	
            $(this).siblings('div.notice').fadeIn();
            return false;
        }
        else {
            $(this).siblings('div.notice').fadeOut();
        }
        
        $.get('ajax/index.html', {
            page: 'shop',
            action: 'paf',
            pcode: postcode,
            house: house_name,
            prefix: this_prefix
        }, function(data){
        		
				if(!data) {
					return false;
				}
				
				fieldset.find('input.postcode_lookup').val('');
				fieldset.find('input.house_name').val('');
				
				if(browser_is_ie6() && $('#cart_continue').length) {
					continue_button =$('#cart_continue').get(0);
					continue_style = continue_button.style; 
				}
				
				if($('#cc_billing_address_id').val('').length) {
					$('#cc_billing_address_id').val('');
				}
				
            var address_div = $('#' + this_prefix + '_address_1').parents('fieldset:first');
            
            if (address_div.length) {
                if (data.length) {
                    address_div.replaceWith(data);
                }
            }
            else {
                $('#' + this_prefix + '_postcode_lookup_holder').parents('div.r1').after(data);
            }
				
        });
    });
    if(browser_is_ie6()) {
		$('.paf_action').unbind();	
	}
	 /*$('.postcode_lookup_holder input').keyup(function(e) {
	 	
		if(e.keyCode!=13)
		{
			return true;
		}
		
		$(this).parents('div:first').siblings("input[type='submit']").click();
		e.preventDefault();
		return false;
	 });*/
	 
    /* Cart display */
    $('#mini_cart p.toggle_details a').bind('click keyup', function(e){
    
        e.preventDefault();
        
        full_details = $(this).parents('p').siblings('div.full_details')
        
        if (full_details.is(':hidden')) {
            full_details.fadeIn();
        }
        else {
            full_details.fadeOut();
        }
        
        toggle_state = $(this).find('span');
        toggle_state.html(toggle_state.html() == 'Sakla' ? 'Göster' : 'Sakla');
        
        toggle_img = $(this).find('img');
        
        toggle_img.attr('src', toggle_img.hasClass('down') ? 'images/arrow_up.png' : 'images/arrow_down.png');
        toggle_img.attr('class', toggle_img.hasClass('down') ? 'up' : 'down');
    });
    
    /* Other amount inputs */
    $('input.other_amount').bind('focus change click', function(e){
        e.preventDefault();
        
        // Select the previous radio when this input is focused
        $(this).parents('li').prev('li').find('input').attr('checked', 'checked');
    });
    
	 /*$('a.thickbox').click(function() {
	 	
	 	interval = setInterval(function() {
			if($('#TB_overlay').length) {
				
				$('#TB_overlay').bgiframe();
				clearInterval(interval);
				
				if($(window).height() <= 600) {
					console.log('hai');
					$('#TB_window #extended_info').css({height:'300px'})
				}
			}
		},1)
	 })*/
	 
    initOverLabels();
});

//--------------------------------------------------
// Adds tracking of external links to google analytics (ga.js)
// This should include downloads such as pdf, mp3 etc as they sit on a different page to
// the page (assets.wwf.org.uk)
// requires jquery for the selectors
// $(document).ready is a jquery function for after page has loaded
$(document).ready(function(){
    arrTagedLinks = new Array();
    $('a[href^="http"]').each //all absolute links
(function(){
        var href = $(this).attr("href");
        if (!href.match(document.domain))//all external links (includes links to assets)
        {
            $(this).click(function() //attach click event to link
            {
                strTrack = '/exlinks/' + href; //build page url to track
                pageTracker._trackPageview(strTrack); //send fake page view to google analytics
            })
        }
    })
})

function check_account(source){

//	 if (source.val().length > 5 && $(".email_login_prompt").attr('id')) {
	 if (source.val().length > 5) {
    	
        $.get("ajax/index-2.html", {
            "page": "login",
            "action": "check_account",
            "email": source.val()
        }, function(response){
        
            if (response == 1) {
            	
                $(".email_login_prompt").show();
                
                href = $(".email_login_prompt a.login").attr("href");
                
                split_href = href.split("&");
                
                if (source.attr("id") == "email") {
                    redirect = "my_account";
                }
                else if (source.attr("id") == "b_email") {
                  	redirect = "checkout";
						}
                
                split_href[1] = "redirect=" + redirect;
                
                href = split_href.join("&");
                
                $(".email_login_prompt a.login").attr("href", href);
                
                //				$('#cart_continue input').attr("disabled","disabled");
            }
            else {
            
                $(".email_login_prompt").hide();
                //				$('#cart_continue input').removeAttr("disabled");
            }
        });
    }
    else {
        $(".email_login_prompt").hide();
        //		$('#cart_continue input').removeAttr("disabled");		
    }
}

function send_new_password(email,cart_id){

    $.get("ajax/index.html", {
        "page": "login",
        "action": "lost_password",
        "email": email,
		  "cart_id": cart_id
    }, function(response){
    
        if (response == 1) {
            $(".email_login_prompt").html("<p>A new password has been sent to your email address</p>" +
            "<p>You may now <a href=\"?page=login&redirect=checkout&cart_id=" + cart_id + "\">Login</a> with your new password</p>");
        }
    });
}

function browser_is_ie6(){

    if (typeof document.body.style.maxHeight === "undefined") {
        return true;
    }
    else {
        return false;
    }
}

function initOverLabels(){
    if (!document.getElementById) 
        return;
    
    var labels, id, field;
    
    // Set focus and blur handlers to hide and show 
    // labels with 'overlabel' class names.
    labels = document.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
    
        if (labels[i].className == 'overlabel') {
        
            // Skip labels that do not have a named association
            // with another field.
            id = labels[i].htmlFor || labels[i].getAttribute('for');
            if (!id || !(field = document.getElementById(id))) {
                continue;
            }
            
            // Change the applied class to hover the label 
            // over the form field.
            labels[i].className = 'overlabel-apply';
            
            // Hide any fields having an initial value.
            if (field.value !== '') {
                hideLabel(field.getAttribute('id'), true);
            }
            
            // Set handlers to show and hide labels.
            field.onfocus = function(){
                hideLabel(this.getAttribute('id'), true);
            };
            field.onblur = function(){
                if (this.value === '') {
                    hideLabel(this.getAttribute('id'), false);
                }
            };
            
            // Handle clicks to label elements (for Safari).
            labels[i].onclick = function(){
                var id, field;
                id = this.getAttribute('for');
                if (id && (field = document.getElementById(id))) {
                    field.focus();
                }
            };
            
        }
    }
};

function hideLabel(field_id, hide){
    var field_for;
    var labels = document.getElementsByTagName('label');
    for (var i = 0; i < labels.length; i++) {
        field_for = labels[i].htmlFor || labels[i].getAttribute('for');
        if (field_for == field_id) {
            labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
            return true;
        }
    }
}
/**
 * Parse url parameters into an object
 * @param {string} url
 * @return {object}
 */
function url_params_to_obj(url) {
	var params = {};
	
	param_string = url.substr(url.indexOf('?')+1);
	key_val_array = param_string.split('&');
	
	for(x in key_val_array) {
		split = key_val_array[x].split('=');
		params[split[0]] = split[1];
	}
	return params;
}