// used for custom events
JLI.events = {};

JLI.components.twoTabPanel = {
    
    hashKey: "open",
    
    init : function() {
        // if not edit mode, create tabs
        if(!JLI.editMode) {
            $('div.twoTabContainer').tabs({
                selected: -1,
                collapsible: true
            });
            
            // unselect and hide other tabs
            $('div.twoTabContainer ul li a').click(function(e) {
                var selected = $(this).parents("div.twoTabContainer:first");
                $('div.twoTabContainer').not($(selected)).tabs('option', 'selected', -1);
                JLI.urlHash.updateState(JLI.components.twoTabPanel.hashKey, this.id);
                JLI.urlHash.pushState();
            });
        }
        
        var open = JLI.urlHash.state[JLI.components.twoTabPanel.hashKey];
        if(open) {
            $('#' + open).click();
            sc_trackBookmark(open);
        }
        
    }
};

JLI.postcodeLookup = {
    // initialize post code lookup
    init: function() {
        // if no postcode components added, don't process
        if(typeof JLI.components.postcode == 'undefined') return;
        
        if(typeof validatePostCode == 'undefined') {
            $.getScript('/etc/designs/jli/js/validatePostCode.js', JLI.postcodeLookup.bindElements);
        } else {
            JLI.postcodeLookup.bindElements();
        }
    },
    
    bindElements: function() {
        $.each(JLI.components.postcode, function(i, p) {
            var input = $('#' + p.id),
                button = $('#' + p.buttonId),
                select = $('#' + p.selectId);
            
            // postcode input field validation
            input.change(function() {
                validatePostCode(this);
            });
            
            // find address via ajax call
            button.click(function(e) {
                e.preventDefault();
                $.getJSON('/jli/ajax/postcodelookup?postCode=' + input.val(), function(data) {
                
                    var addressToArray = function(address) {
                        var v = [];
                        for ( var j in address) {
                            if (address[j])
                                v.push(address[j]);
                        }
                        return v;
                    };
                    
                    // if no errors, load addresses in dropdown
                    if(data[0]) {
                        var addresses = data[0].addressList,
                            dropdown = select.parents('div.postCodeDropdown:first');
                        
                        $('option:not(:first)', select).remove();
                        
                        if(addresses.length > 1) {
                            
                            dropdown.show();
                            $.each(addresses, function(i, item) {
                                var v = addressToArray(item);
                                select.append('<option>' + v.join(' - ') + '</option>');
                            });
                            
                        } else {
                            
                            dropdown.hide();
                            var v = addressToArray(addresses[0]);
                            for ( var j in p.addressIds ) {
                                if ( v[j] ) {
                                    $('#' + p.addressIds[j]).val(v[j]);
                                }
                            }
                        
                        }
                    } else {
                        alert("We were unable to find address.\nPlease enter your address manually.");
                    }
                });
            }).css('display', 'inline-block');
            
            
            // if address fields are specified, populate with selected address from dropdown
            if(p.addressIds.length > 0) {
                select.change(function() {
                    var address = $('option:selected', this).text().split(' - ');
                    for ( var j in p.addressIds ) {
                        if ( address[j] ) {
                            $('#' + p.addressIds[j]).val(address[j]);
                        }
                    }
                });
            }
        });
    }
};

JLI.competition = {
    validateForm: function() {
    
        $('#competition_id').submit(function() {
            
        	$(this).find('p.form_error').remove();
        	
            // validate date fields
            var validDate = /^(0[1-9]|1[012])\/(19|20)\d{2}$/;
            var errorCount = 0, validForm = true;
            var dateFields = $(this).find('select.date');
            dateFields.each(function() {
                if (!validDate.test($(this).val())) {
                    errorCount++;
                }
            });
            
            if ( errorCount >= dateFields.length ) {
                var dateParents = dateFields.parent();
                
                var existingErrors = dateParents.siblings('div.fieldErrorDesc');
                
                if(existingErrors.length == 0) {
                    $("<span class=\"fieldError\">!</span>").insertAfter(dateFields);
                    $("<div class=\"fieldLeft\">&nbsp;</div><div class=\"fieldErrorDesc\">Please enter your car insurance or home insurance renewal date, or both</div>").insertAfter(dateParents);
                }
                
                // insert form error message at top
                dateParents.parents('form:first').prepend('<p class="form_error">Please correct the fields marked ( <span class="fieldError">!</span> ) to continue. Thank you.</p>');
                
                validForm = false;
            }
            
            return validForm;
        
        });
    }
};

JLI.csForms = {
    init: function() {
        JLI.csForms.feedback();
        JLI.csForms.headOffice();
        JLI.csForms.changeDetails();
    },
    
    feedback: function() {
        var emailDiv = $('#feedback_form_EMAIL').parents('div.formRow:first').hide();
        $('div.feedbackForm input.radio').click(function() {
            JLI.csForms.radioToggleField(this, 'yes', emailDiv);
        });
        if ($('#v_yes:checked').length == 1) $('#feedback_form_EMAIL').parents('div.formRow:first').show();
    },
    
    headOffice: function() {
        var repDiv = $('#head_office_form_REP').parents('div.formRow:first');
        $('div.headOfficeForm input.radio').click(function() {
            JLI.csForms.radioToggleField(this, 'complaint', repDiv);
        });
        
    },
    
    changeDetails: function() {
        var iNote = $('#insurance-note').hide(),
            cNote = $('#car-note').hide(),
            pNote = $('#policies-note').hide(),
            checked = [];
            
        var updateChecked = function(name, action) {
        
            var toggle = $('#change_details_form_' + name).parents('div.formRow:first');
        
            if(action == 'add' && $.inArray(name, checked) < 0) {
                checked.push(name);
                toggle.show();
            } else if (action == 'remove' && $.inArray(name, checked) != -1) {
                checked = $.grep(checked, function(value) {
                    return value != name;
                });
                toggle.hide();
            }
            
            // insurance note
            if($.inArray('HOME', checked) != -1 || $.inArray('SPECIALIST', checked) != -1 || $.inArray('PET', checked) != -1 || $.inArray('TRAVEL', checked) != -1) {
                iNote.show();
            } else {
                iNote.hide();
            }
            // car insurance note
            if($.inArray('CAR', checked) != -1) {
                cNote.show();
            } else {
                cNote.hide();
            }
            // policy number note
            if(checked.length > 0) {
                pNote.show();
            } else {
                pNote.hide();
            }
        };
            
        $('div.changeDetailsForm input.checkbox').click(function() {
            var check = $(this),
                name = check.attr('id').split('_')[1];
                
            if(check.attr('checked')) {
                updateChecked(name, 'add');
            } else {
                updateChecked(name, 'remove');
            }
            
        }).each(function() {

            $('#change_details_form_' + $(this).attr('id').split('_')[1]).parents('div.formRow:first').hide();
            
        }).removeAttr('checked');
        
    },
    
    radioToggleField: function(field, value, toggleElement) {
        field = $(field);
        toggleElement = $(toggleElement);
                
        if(field.attr('checked')) {
            if(field.attr('value') == value) {
                toggleElement.show();
            } else {
                toggleElement.hide();
            }
        }
    }
};

JLI.ie = {
    isIE: $.browser.msie && $.browser.version < 8,
    fixButtons: function() {
        if(this.isIE) {
            $(".button > span").each(function(){
                var me = $(this), anchor = me.parent(), w;

                if( anchor.hasClass('button80') ) {
                    w = 43;
                } else if( anchor.hasClass('button125') ) {
                    w = 88;
                } else if( anchor.hasClass('button145') ) {
                    w = 114;
                }
                if(me.attr('scrollWidth') < w) {
                    me.css('width', w + 'px');
                }
            });
        }
    }
};

JLI.brandPhoneNumber = {

    key: "brand",
    path: "path:/etc/jli/globals/jcr:content/mainpar/phonelist",
    locale: "tel800",
    props: "brandId,tel800,telGeo",
    data: {},
    
    init: function() {
        
        var cookie = $.readCookie('brand');
        
        if(cookie) {
            this.data = this.getBrandCookieObj(cookie);
        }
    
        var brands = JLI.urlHash.state[JLI.brandPhoneNumber.key];
        if(brands) {
            var brand = brands.split("|");
            for( var i = 0; i < brand.length; i++) {
            
                $.getJSON('/jli/ajax/gorabbit?query=' + JLI.brandPhoneNumber.path + " brandId:" + brand[i] + "&props=" + JLI.brandPhoneNumber.props, function(data) {
                    if(data.results > 0) {
                        var r = data.hits[0];
                        var product = JLI.brandPhoneNumber.getProductByBrandId(r.brandId);
                        
                        if(product) {
                        
                            if(typeof JLI.brandPhoneNumber.data[product] == 'undefined' || JLI.brandPhoneNumber.data[product].brandId != r.brandId) {
                                var brandObj = { "brandId": r.brandId, "tel800": r.tel800, "telGeo": r.telGeo};
                                JLI.brandPhoneNumber.data[product] = brandObj;
                                JLI.brandPhoneNumber.updateBrand(brandObj, product, JLI.brandPhoneNumber.locale);
                                JLI.brandPhoneNumber.updateBrandCookie(JLI.brandPhoneNumber.data);
                            }
                        }
                    }
                });
            }
        }

        this.updateBrandElements(this.data, this.locale);
    },
    
    getBrandCookieObj: function(cookie) {
        var brands = cookie.split(','), obj = {};
            
        for(var i = 0; i < brands.length; i++) {
            var b = brands[i].split('|');
            if(b.length > 3) {
                obj[b[0]] = {"brandId": b[1], "tel800": b[2], "telGeo": b[3] };
            }
            
        }
        return obj;
    },
    
    updateBrandCookie: function(data) {
        var value = "";
        
        if(data) {
            for( var i in data ) {
                value += i + "|" + data[i].brandId + "|" + data[i].tel800 + "|" + data[i].telGeo + ",";
            }
            $.setCookie("brand", value, {duration: 30 });
        }
    },
    
    updateBrandElements: function(data, locale) {
        if(data) {
            for( var i in data) {
                this.updateBrand(data[i], i, locale);
            }
        }
    },

    updateBrand: function(brand, type, locale) {
        var number = brand[locale];

        $("strong.brandNumber." + type).text(number);
        $("a.brandLink." + type).each(function() {
            var href = $(this).attr("href");
            var url = $.param.querystring(href, "brand=" + brand.brandId.substring(1), 1);
            $(this).attr("href", url);
        });
    },
    
    getProductByBrandId: function(id) {
        var char = id.charAt(0),
            product = null;
        
        if(char) {
            switch(char) {
                case "H":
                    product = "home";
                    break;
                case "S":
                    product = "specialist";
                    break;
                case "C":
                    product = "car";
                    break;
                case "P":
                    product = "pet";
                    break;
                case "T":
                    product= "travel";
                    break;
                case "L":
                    product= "life";
                    break;
                case "E":
                    product= "event";
                    break;
                case "W":
                    product= "wedding";
                    break;
            }
        }
        
        return product;
        
    }
};

JLI.lifeCover = {
    calculate: function() {
        var monthlySum = 0,
            yearlySum = 0,
            requiredSum = 0,
            pound = "&pound;";

        //iterate through each textboxes and add the values
        $("div.lifeCoverCalculator input.text").each(function() {
        //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0) {
                monthlySum += parseFloat(this.value);
            }
        });

        yearlySum = monthlySum * 12;
        requiredSum = yearlySum * 20;
        //.toFixed() method will roundoff the final sum to 2 decimal places
        $("div.lifeCoverCalculator div.results span.monthly").html(pound+monthlySum.toFixed(2));
        $("div.lifeCoverCalculator div.results span.yearly").html(pound+yearlySum.toFixed(2));
        $("div.lifeCoverCalculator div.totals span.total").html(pound+requiredSum.toFixed(2));
    },
    init: function() {
        // reset
        $('div.lifeCoverCalculator div.compute span.reset').click(function() {
            $("div.lifeCoverCalculator input.text").val('');
            JLI.lifeCover.calculate();
        });

        // calculate
        $('div.lifeCoverCalculator div.compute a').click(function(e) {
            e.preventDefault();
            JLI.lifeCover.calculate();
        });
    }
};

JLI.anchors = function() {
    // anchors with new window size
    $('a.windowNew').click(function(e){
        var a = $(this), classes = a.attr("class").split(' '), c;
        for(var i = 0; i < classes.length; i++) {
            if(classes[i].indexOf('w-') != -1) {
                c = classes[i];
                break;
            }
        }
        if(c) {
            var size = c.split('-'), width = size[1], height = size[2];
            if(width && height) {
                e.preventDefault();
                window.open(a.attr('href'), 'w', 'width=' + width + ',height=' + height + ',scrollbars=yes');
            }
        }
    });
    // styled link list anchors
    $('div.styledLinkList li a').click(function(e){
        var me = $(this), target = me.attr('target');
        if(target) {
            e.preventDefault();
            window.open(me.attr('href'), target, 'width=1024,height=768,scrollbars=yes');
        }
    });
};

JLI.urlHash = {
    
    // holds name value pairs
    state: {},

    init: function() {
        JLI.urlHash.state = $.deparam.fragment();
        $(JLI.events).trigger("hashdone", [JLI.urlHash.state]);
    },
    
    updateState: function(name, value) {
        JLI.urlHash.state[name] = value;
    },
    
    pushState: function() {
        $.bbq.pushState(JLI.urlHash.state);
    },
    
    getState: function(name) {
        return JLI.urlHash.state[name];
    }
};

$(document).ready(function (){
    JLI.urlHash.init();
    JLI.components.twoTabPanel.init();
    JLI.postcodeLookup.init();
    JLI.competition.validateForm();
    JLI.csForms.init();
    JLI.lifeCover.init();
    JLI.anchors();
    JLI.brandPhoneNumber.init();
    JLI.ie.fixButtons();
});

$(window).load(function() {
    $('img.pngfix').ifixpng("/etc/designs/jli/images/blank.gif");
    if(navigator.userAgent.toLowerCase().indexOf('chrome')== -1){
        if (/^Win/.test(navigator.platform) && $.browser.safari) {
	    $('.funnelForm button[name="submit"][type="submit"] span').css('margin-top', -1);
        }
    }	    
});
