// Replace $ with $$jq to stop sitecore conflicts

var $$jq = jQuery.noConflict();



// Image cycle 

$$jq(function() {
    $$jq('#fade-images').cycle({
        fx: 'fade',
        speed: 4000
    });
});

$$jq(function() {
    $$jq('#header-image-dynamic').cycle({
        fx: 'fade',
        speed: 4000
    });
});

$$jq(function() {
    $$jq('#environment-fader-right').cycle({
        fx: 'fade',
        speed: 4000,
        pause: 0,
        speedIn: 1000,
        speedOut: 1000,
        pager: '#environment-fader-left',
        pagerEvent: 'mouseover',
        pauseOnPagerHover: 1,
        allowPagerClickBubble: true,
        pagerAnchorBuilder: function(idx, slide) {
            return '#environment-fader-left a:eq(' + idx + ')';
        }
    });
});

$$jq(function() {
    $$jq('.mostReadCarousel').cycle({
        fx: 'scrollHorz',
        activePagerClass: 'active',
        pager: '.pager .numbers',
        prev: '.prev',
        next: '.next',
        pause: true
    });
});

// Google maps local seach amends
$$jq(document).ready(function() {
    setTimeout("checkForItem()", 200);
});
var timeoutCount = 0;
function checkForItem() {
    timeoutCount++;
    if (($$jq('input.gels-input').val() == null || $$jq('input.gels-input').val() == "undefined") && timeoutCount < 50) {
        setTimeout("checkForItem()", 200);
     } else {
        makeGoogleSearchLocal();
     }
}
function makeGoogleSearchLocal(){
    $$jq('input.gels-input').css("display", "none");
    $$jq('input.gels-input')
            .after("<input type='text' value='search the map' title='search' id='IgSearchInput' class='gels-input' name='IgSearch' value=' ' />");
    //Add event handlers for our field after it has been added to the dom.
    $$jq('#IgSearchInput').click(function() {
        if ($$jq('#IgSearchInput').val() == "search the map") {
            $$jq('#IgSearchInput').val("");
        }
    });
    $$jq('#IgSearchInput').keypress(function(event) {
        $$jq('input.gels-input:hidden').val($$jq('#IgSearchInput').val() + " ,UK");
        //force the form search on enter press after search term has been set.
        if (event.keyCode == '13') {
            event.preventDefault();
            $$jq('input.gels-button').click();
        }
    });
    
}

// Image replacement on hover

$$jq(document).ready(function() {
    $$jq("#nav_level-1 > ul > li").hover(function() {
        var imgHoverable = $$jq(this).find('.imgHoverable').attr("src");
        if (imgHoverable != null) {
            var hoverImg = HoverImgOf(imgHoverable);
            $$jq(this).find('.imgHoverable').attr("src", hoverImg);
        }
    }, function() {
        var imgHoverableAlt = $$jq(this).find('.imgHoverable').attr("src");
        if (imgHoverableAlt != null) {
            var normalImg = NormalImgOf(imgHoverableAlt);
            $$jq(this).find('.imgHoverable').attr("src", normalImg);
        }
    }
   );
});
function HoverImgOf(filename) {
    var re = new RegExp("(.+)\\.(gif|png|jpg|ashx)", "g");
    return filename.replace(re, "$1_hover.$2");
}
function NormalImgOf(filename) {
    var re = new RegExp("(.+)_hover\\.(gif|png|jpg|ashx)", "g");
    return filename.replace(re, "$1.$2");
}

// Image replacement when selected

$$jq(document).ready(function() {
    if ($$jq("#nav_level-1 li.selected a img").attr("src") != null) {
        var origImgSrc = $$jq("#nav_level-1 li.selected a img").attr("src");
        var origImgSplit = origImgSrc.split(".");
        var NewImgSrc = origImgSplit[0] + "_hover." + origImgSplit[1];
        $$jq("#nav_level-1 li.selected a img").attr("src", NewImgSrc);
    }
});


// News ticker


$$jq(document).ready(function() {
    createTicker();

});

function createTicker() {

    var tickerLIs = $$jq("#latest-news ul").children();
    tickerItems = new Array();
    tickerLIs.each(function(el) {
        tickerItems.push(jQuery(this).html());
    });
    i = 0
    rotateTicker();
}

function rotateTicker() {
    if (i == tickerItems.length) {
        i = 0;
    }
    tickerText = tickerItems[i];
    c = 0;
    typetext();
    setTimeout("rotateTicker()", 10000);
    i++;
}

var isInTag = false;
function typetext() {

    if (tickerText != null) {
        var thisChar = tickerText.substr(c, 1);
        if (thisChar == '<') { isInTag = true; }
        if (thisChar == '>') { isInTag = false; }
        $$jq('#latest-news').html("&nbsp;" + tickerText.substr(0, c++));
        if (c < tickerText.length + 1)
            if (isInTag) {
            typetext();
        } else {
            setTimeout("typetext()", 28);
        }
        else {
            c = 1;
            tickerText = "";
        }
    }
}


// Tab switcher

$$jq(document).ready(function() {
    $$jq("#product-tabs a span").click(function(e) {
        var id = e.target.parentNode.parentNode.id;
        var showElement = id.split("-");
        switchTabs(showElement[0]);
        return false;
    });
    var firstId = $$jq("#product-tabs ul li").attr("id");
    if (firstId != null) {
        var firstItem = firstId.split("-");
        switchTabs(firstItem[0]);
    }
});

function switchTabs(area) {
    updateSamplesSummary();
    if (samplesCount > 4) {
        alert('Sorry, you may only select a maximum of 4 samples.');
    }
    else {
        hideAllContent();
        var tabId = "#" + area + "-tab a";
        var contentId = "#" + area + "-content";
        $$jq(tabId).addClass("selected");
        $$jq(contentId).addClass("active");
        loadSifrFonts();
    }
    return false;
}
function hideAllContent() {
    $$jq("[ID$='-content']").removeClass("active");
    $$jq("#product-tabs a").removeClass("selected");
    return false;
}
function activeTabId(tabId) {
    var clickSelector = "#product-tabs #" + tabId + " a";
    $$jq(clickSelector).click();
    return false;
}

var samplesCount;

function updateSamplesSummary() {
    var samplesHtml = "";
    var panelsHtml = "";
    var brochuresHtml = "";
    var samplesEmail = "";
    var panelsEmail = "";
    var brochuresEmail = "";

    var brochuresElements = $$jq('#brochure-content input:checkbox:checked');
    $$jq.each(brochuresElements, function(i, brochure) {
        var brochureName = $$jq(brochure).closest("span").attr("displayname");
        brochuresHtml += brochureName + "</br>";
        brochuresEmail += brochureName + " | ";
    });
    
    var samplesElements = $$jq('.chkSample input:checkbox:checked');
    $$jq.each(samplesElements, function(i, sample) {
        var sampleName = $$jq(sample).closest("span").attr("displayname");
        samplesHtml += sampleName + "</br>";
        samplesEmail += sampleName + " | ";
        
    });

    samplesCount = samplesElements.length;

    var panelsElements = $$jq('.chkPanel input:checkbox:checked');
    $$jq.each(panelsElements, function(i, panel) {
        var panelName = $$jq(panel).closest("span").attr("displayname");
        panelsHtml += panelName + "</br>";
        panelsEmail += panelName + " | ";
    });

    $$jq("#contact-content .samples .info").html(samplesHtml);
    $$jq("#contact-content .colourpanels .info").html(panelsHtml);
    $$jq("#contact-content .brochures .info").html(brochuresHtml);

    $$jq("#hiddenSamples").val(samplesEmail);
    $$jq("#hiddenPanels").val(panelsEmail);
    $$jq("#hiddenBrochures").val(brochuresEmail);
}

$$jq.fn.fix_radios = function() {
    function focus() {
        // if this isn't checked then no option is yet selected. bail
        if (!this.checked) return;

        // if this wasn't already checked, manually fire a change event
        if (!this.was_checked) {
            $$jq(this).change();
        }
    }

    function change(e) {
        // shortcut if already checked to stop IE firing again
        if (this.was_checked) {
            e.stopImmediatePropagation();
            return;
        }

        // reset all the was_checked properties
        $$jq("input[name=" + this.name + "]").each(function() {
            this.was_checked = this.checked;
        });
    }

    // attach the handlers and return so chaining works
    return this.focus(focus).change(change);
}

// attach it to all radios on document ready
$$jq(function() {
    $$jq("input[type=radio]").fix_radios();
});

$$jq(document).ready(function() {
    $$jq("#contact-content .OrganisationTypeDdl").change(function() {
        var selectedVal = $$jq(this).val();
        if (selectedVal == "Other") {
            $$jq("#contact-content .OtherOrgType").show();
        }
        else {
            $$jq("#contact-content .OtherOrgType").hide();
        }
    });

    $$jq("#contact-content .ProjectTypeDdl").change(function() {
        var selectedVal = $$jq(this).val();
        if (selectedVal == "Other") {
            $$jq("#contact-content .projecttypeother").show();
        }
        else {
            $$jq("#contact-content .projecttypeother").hide();
        }
    });

    $$jq("#contact-content .ProjectDetailRadio input:radio").change(function() {
        var selectedVal = $$jq(this).val();
        if (selectedVal == "Yes") {
            $$jq("#contact-content .type").show();
            $$jq("#contact-content .projecttype").show();
            $$jq("#contact-content .privatepublic").show();
            $$jq("#contact-content .projectlocation").show();
            $$jq("#contact-content .projectdetails").show();
            $$jq("#contact-content .qualifyHeading").show();
        }
        else {
            $$jq("#contact-content .type").hide();
            $$jq("#contact-content .projecttype").hide();
            $$jq("#contact-content .privatepublic").hide();
            $$jq("#contact-content .projectlocation").hide();
            $$jq("#contact-content .projectdetails").hide();
            $$jq("#contact-content .projecttypeother").hide();
            $$jq("#contact-content .qualifyHeading").hide();
        }
    });
});
    
// Colour picker

$$jq(document).ready(function() {
    //add a class to every element for a unique grabber
    $$jq(".thumbs-wrapper").each(function(index) {
        $$jq(this).attr("id", "thumbsCont" + index);

        var main_image = $$jq(".main_view img", this).first();
        var mini_image_li = $$jq("ul.thumb li", this).first();
        var mini_image_href = $$jq("a", mini_image_li).attr("href");

        if (mini_image_href != null) {
            main_image.attr({ src: mini_image_href });
            mini_image_li.addClass("selected");
        }
        $$jq(".colour-txt", this).text($$jq("ul.thumb li.selected a", this).attr("title"));
    });

    $$jq("ul.thumb li a").click(function(e) {
        var containerId = e.currentTarget.parentNode.parentNode.parentNode.id;
        $$jq("#" + containerId + " ul.thumb li").removeClass("selected");
        $$jq(this.parentNode).addClass("selected");
        $$jq("#" + containerId + " .colour-txt").text($$jq(this).attr("title"));

        var mainImage = $$jq(this).attr("href"); //Find Image Name
        $$jq("#" + containerId + " .main_view img").attr({ src: mainImage });
        return false;
    });
});


// Slide open div on click

$$jq(document).ready(function() {
    $$jq(".link-large").click(
       function() {
           $$jq(this).toggleClass("active");
           $$jq(this.parentNode).next("div.content-toggled").slideToggle(300);
           loadSifrFonts();
       });
});


function openContentSection(tab, section) {
    var sectionName = "#" + tab + "-" + section + " " + ".content-toggled";
    var linkLargeName = "#" + tab + "-" + section + " " + ".link-large";
    var section = $$jq(sectionName);
    var linkLarge = $$jq(linkLargeName);
    linkLarge.addClass("active");
    section.slideDown(300);
    loadSifrFonts();
    return false;
}


$$jq(document).ready(function() {
    $$jq(".faqs-title").click(
       function() {
           $$jq(this).toggleClass("active");
           $$jq(this).next("div.faqs-content").slideToggle(300);
           loadSifrFonts();
       });
});


// Lightbox 

$$jq(document).ready(function() {
    $$jq('.fitting-img a').lightBox();

    $$jq(".fitting-img").each(function() {
        var img = $$jq(this).find("img");
        var a = $$jq(this).find("a");
        a.attr("href", img.attr("src"));
    });
});



// Content columns 

$$jq(document).ready(function() {
    var contentarea = $$jq("#content-area");
    var firstcol = $$jq("div[id^='main-content-']", contentarea).first();
    var rightcontentarea = $$jq("#right-content");

    if (contentarea != null) {
        var contentarea_width = contentarea.width();
    }

    if (firstcol != null) {
        var firstcol_width = firstcol.outerWidth(true);
    }

    if (rightcontentarea != null) {
        var rightcontentarea_margin_left_string = rightcontentarea.css("margin-left");
        if (rightcontentarea_margin_left_string != null) {
            var rightcontentarea_margin_left = rightcontentarea_margin_left_string.replace("px", "");
        }
    }

    if (contentarea_width != null && firstcol_width != null && rightcontentarea_margin_left != null) {
        rightcontentarea.width(contentarea_width - firstcol_width - rightcontentarea_margin_left);
    }
});


// Main Navigation drop down menu
$$jq(document).ready(function() {
    var toggle = function(direction, display) {
        return function() {
            var self = this;
            var ul = $$jq("ul", this);
            if (ul.css("display") == display && !self["block" + direction]) {
                $$jq(this).addClass("active");
                self["block" + direction] = true;
                ul["slide" + direction]("fast", function() {
                    self["block" + direction] = false;
                    if (ul.css("display") == "none") {
                        $$jq(this).parent().removeClass("active");
                    }
                });
            }
        };
    }
    $$jq(".top-navigation ul li").hover(toggle("Down", "none"), toggle("Up", "block"));
    $$jq(".top-navigation ul li ul").hide();
});

$$jq(document).ready(function() {
    $$jq(".newsletterBlock .title a").click(function(e) {
       e.preventDefault();
       $$jq(this).toggleClass("active");
       if ($$jq(this).hasClass('active')) {
           $$jq(this.parentNode).next("div.subscribe").animate({
               height: 'show'
           }, 600);
       }
       else {
           $$jq(this.parentNode).next("div.subscribe").animate({
               height: 'hide'
           }, 600);
       }
    });
});

$$jq(document).ready(function() {
    $$jq(".newsletterBlock .subscribe .email").focus(function() {
        $$jq(this).val('');
    });
});
