$("a.#lnkAdvancedDealerSearch").click(function() {
    $("div.campaigns").toggle("normal");
});


$.parseQuery = function(qs, options) {
    var q = (typeof qs === 'string' ? qs : window.location.search), o = { 'f': function(v) { return unescape(v).replace(/\+/g, ' '); } }, options = (typeof qs === 'object' && typeof options === 'undefined') ? qs : options, o = jQuery.extend({}, o, options), params = {};
    jQuery.each(q.match(/^\??(.*)$/)[1].split('&'), function(i, p) {
        p = p.split('=');
        p[1] = o.f(p[1]);
        params[p[0]] = params[p[0]] ? ((params[p[0]] instanceof Array) ? (params[p[0]].push(p[1]), params[p[0]]) : [params[p[0]], p[1]]) : p[1];
    });
    return params;
}

function getGPS() {
    if (geo_position_js.init()) {
        geo_position_js.getCurrentPosition(success_callback, error_callback, { enableHighAccuracy: true, options: 5000 });
    } else {
        alert($('p#dealer_search_functionality_not_supported').html());
    }
}

function success_callback(p) {
    $('#keyword-location').val(p.coords.latitude + ',' + p.coords.longitude);
    $('#keyword').val('');
    $('form#dealerform-proximity').submit();
}

function error_callback(p) {
    alert($('p#dealer_search_no_location_found').html());
}

function insertGeocode(objForm, formId) {
    var countryname = objForm.countryname.value;
    var keyword = objForm.keyword.value;

    if (keyword != "") {
        //countryname = countryname.replace(" /", "/");
        //countryArray = countryname.split("/");

        //for (i = 0; i < countryArray.length; i++) {
        var country = countryname;
        if ($('input:radio[name=country_variant]:checked').val() != undefined) {
        country = $('input:radio[name=country_variant]:checked').val();
        }

        if (country == "UK") { country = "United Kingdom"; }
        locationString = keyword + ", " + country;

        // get gps
        var myGeocoder = new GClientGeocoder();
        myGeocoder.getLocations(locationString, function(response) {
            var bFound = false;
            var lowestAccurracyFound = 10;
            if (response.Placemark != undefined && response.Placemark.length > 0) {
                for (i = 0; i <= response.Placemark.length - 1; i++) {
                    place = response.Placemark[i];
                    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                    accuracy = place.AddressDetails.Accuracy;
                    if (point && accuracy <= 5 && accuracy < lowestAccurracyFound) {
                        $('#keyword-location').val(place.Point.coordinates[1] + ',' + place.Point.coordinates[0]);
                        $('#keyword').val('');
                        $('#keyword-original').val(keyword);
                        bFound = true;
                        lowestAccurracyFound = accuracy;
                    }
                }
            }

            if (bFound == false) {
                // nothing found
                $('#keyword-location').val('');
            }
            $('form#' + formId).submit();
        });
        //}
    }
}


function isValidKeepMePostedForm(objForm, strIntroText) {
    var strErrors = "";

    strErrors += ensureRadio(objForm, "Name_Prefix", "lblName_Prefix");
    strErrors += ensureInput(objForm, "Name_Full", "lblName_Full");
    strErrors += ensureEmailAddress(objForm, "Email", "lblEmail");

    if (strErrors != "") {
        alert(strIntroText + ": \n\n" + strErrors);
        return false;
    } else {
        return true;
    }
}


function isValidContactForm(objForm, strIntroText) {
    var strErrors = "";

    strErrors += ensureInput(objForm, "Name_First", "lblName_First");
    strErrors += ensureInput(objForm, "Name_Last", "lblName_Last");
    strErrors += ensureInput(objForm, "Giant_Model", "lblGiant_Model");
    strErrors += ensureInput(objForm, "City", "lblCity");
    strErrors += ensureEmailAddress(objForm, "Email", "lblEmail");

    if (strErrors != "") {
        alert(strIntroText + ": \n\n" + strErrors);
        return false;
    } else {
        return true;
    }
}



function changeBorder(objImage, strNewState) {
    if (strNewState == "on") {
        objImage.style.border = "3px solid #aaaaaa";
        //objImage.style.border = "3px solid #00B4F7";
    }
    else {
        objImage.style.border = "3px solid #878787";
    }
}

function hoverOn(objDiv) {
    objDiv.style.backgroundColor = "#F2F2F2";
}

function hoverOff(objDiv) {
    objDiv.style.backgroundColor = "#EEEEEE";
}

function boxHoverOn(objDiv) {
    objDiv.style.background = "#EEEEEE";
}

function boxHoverOff(objDiv) {
    objDiv.style.background = "url(/images/bg_technologybox.gif) repeat-x";
}

function serieHoverOn(serieID) {
    imageID = "serie_image_" + serieID;
    setImageMargin(imageID, 'on');
}

function serieHoverOff(serieID) {
    imageID = "serie_image_" + serieID;
    setImageMargin(imageID, 'off');
}

function doResultHover(objDiv, onOrOff) {
    var currentClasses = objDiv.className;

    if (onOrOff == "on") {
        objDiv.className = currentClasses + " item-hover";
    } else if (onOrOff == "off") {
        objDiv.className = currentClasses.replace("item-hover", "");
    }

}


function setZoomImage(imageID, onOrOff) {
    objImage = document.getElementById(imageID);
    myWidth = objImage.width;
    myHeight = objImage.height;
    mySrc = objImage.src;
    mySrc = mySrc.replace("100", "225");

    objSpacer = document.getElementById("spacer");

    objSpacer.width = "225";
    objSpacer.height = "100";
    objSpacer.src = mySrc;

    objSpacer.style.top = 100;
    objSpacer.style.position = "absolute";
}


/*
function setLinkColor(linkID, colorCode)
{	
objLink = document.getElementById(linkID);
objLink.style.color = colorCode;
}
*/

function setImageMargin(imageID, onOrOff) {
    objImage = document.getElementById(imageID);

    if (onOrOff == "on") {
        objImage.style.margin = "10px 10px 10px 13px";
    } else {
        objImage.style.margin = "10px 10px 10px 10px";
    }
}


function goToPage(url) {
    window.location.href = url;
}

function removeInitialText(objInput) {
    objInput.value = "";
    objInput.style.color = "#000000";

}

function hoverOnImage(objImage) {
    currentSource = "" + objImage.src;
    objImage.src = currentSource.replace(".gif", "_hover.gif");
}

function hoverOffImage(objImage) {
    currentSource = "" + objImage.src;
    objImage.src = currentSource.replace("_hover.gif", ".gif");
}

function setBikeExtraImage(strSourceOfImage, strSourceOfZoom) {
    //get object
    hideElement("product-main-image");
    showElement("product-extra-image");

    //define new style
    newBackgroundStyle = "url('" + strSourceOfImage + "') 50% 1% no-repeat"

    //set background
    objDiv = document.getElementById("product-extra-image");
    objDiv.style.background = newBackgroundStyle;

    // change link for magic zoom
    objLinkZoom = document.getElementById("zoom2")
    objLinkZoom.href = strSourceOfZoom;
}

function setMainImageNew(strSourceOfImage, whichImage) {
    //set image
    objImage = document.getElementById("myImage");
    objImage.src = strSourceOfImage;

    // change link for magic zoom
    objLinkZoom = document.getElementById("zoom-link")
    currentZoomHref = objLinkZoom.href;
    firstPart = currentZoomHref.substring(0, currentZoomHref.lastIndexOf("?image="));
    secondPart = currentZoomHref.substring(currentZoomHref.lastIndexOf("&modal="));
    newZoomHref = firstPart + "?image=" + whichImage + secondPart;

    // set new link
    objLinkZoom.href = newZoomHref;
}

function setMainImageAndChangeZoomLink(strNewSourceOfImage, strNewSourceOfZoomImage) {
    //set image
    objImage = document.getElementById("myImage");
    objImage.src = strNewSourceOfImage;

    // change link for jquery zoom
    objLinkZoom = document.getElementById("main-image-zoom-link");
    objLinkZoom.href = strNewSourceOfZoomImage;
}

function resetBikeMainImage() {
    //get object
    showElement("product-main-image");
    hideElement("product-extra-image");
}

function setMainNewsImage(newSource) {
    objImage = document.mainimage;
    objImage.src = newSource;
}

function setMainNewsImageZoomLink(newLink) {
    objZoomLink = document.getElementById("main-image-zoom-link");
    objZoomLink.href = newLink;
}

function showElement(strElementID) {
    objElement = document.getElementById(strElementID);
    if (objElement != null) {
        objElement.style.visibility = "visible";
        objElement.style.display = "block";
    }
}

function hideElement(strElementID) {
    objElement = document.getElementById(strElementID);

    if (objElement != null) {
        objElement.style.visibility = "hidden";
        objElement.style.display = "none";
    }
}

function showTab(strElementID) {
    //hide all
    hideAllTabs();

    // show 1
    showElement(strElementID)

    // change tab state
    setClassName(strElementID + "-tab", "active")
}


function hideAllTabs(strElementID) {
    //reset tab content
    hideElement("overview");
    hideElement("fullspecs");
    hideElement("geometry");
    hideElement("video");
    hideElement("press");
    hideElement("download");

    //reset tab state
    setClassName("overview-tab", "")
    setClassName("fullspecs-tab", "")
    setClassName("geometry-tab", "")
    setClassName("video-tab", "")
    setClassName("press-tab", "")
    setClassName("download-tab", "")
}


function setClassName(strElementID, strClassName) {
    objElement = document.getElementById(strElementID)
    if (objElement != null) {
        objElement.className = strClassName;
    }
}


/* BLOCKS */

function showBlock(strElementID, blnChangeLink, blnChangeIcon, strHideText, blnSlide) {
    if (blnSlide) {
        Effect.SlideDown(strElementID, { duration: 0.25 });
    } else {
        showElement(strElementID);
    }

    if (blnChangeIcon) {
        setImageToMinus(strElementID);
    }
    if (blnChangeLink) {
        changeLinkText(strElementID, strHideText);
    }
}

function hideBlock(strElementID, blnChangeLink, blnChangeIcon, strShowText, blnSlide) {
    if (blnSlide) {
        Effect.SlideUp(strElementID, { duration: 0.25 });
    } else {
        hideElement(strElementID);
    }
    if (blnChangeIcon) {
        setImageToPlus(strElementID);
    }
    if (blnChangeLink) {
        changeLinkText(strElementID, strShowText);
    }
}


function toggleElement(strElementID, blnChangeLink, blnChangeIcon, strShowText, strHideText, blnSlide) {
    objElement = document.getElementById(strElementID);
    strCurrentState = objElement.style.display;

    if ((strCurrentState == "none") || (strCurrentState == "")) {
        //hideAllBlocks(blnChangeLink, blnChangeIcon);
        showBlock(strElementID, blnChangeLink, blnChangeIcon, strHideText, blnSlide);
    } else {
        hideBlock(strElementID, blnChangeLink, blnChangeIcon, strShowText, blnSlide);
    }
}

function toggleModelList(strElementID) {
    toggleElement(strElementID, false, false, '', '', true);
}

function toggleModelBlocks(strElementID, strShowText, strHideText) {
    toggleElement(strElementID, true, true, strShowText, strHideText, false);
}

function toggleElementAndChangeLink(strElementID, strShowText, strHideText) {
    toggleElement(strElementID, true, true, strShowText, strHideText, false);
}

function toggleSubCategorySerie(strElementID, strShowText, strHideText) {
    toggleElement(strElementID, true, true, strShowText, strHideText, false);
}


function setImageToPlus(strElementID) {
    setPlusMinusImage(strElementID, "plus");
}

function setImageToMinus(strElementID) {
    setPlusMinusImage(strElementID, "minus");
}

function setPlusMinusImage(strElementID, newState) {
    //img
    objImage = document.getElementById(strElementID + "plus");

    curImgSrc = "" + objImage.src;

    if (curImgSrc.indexOf("plus") > -1) {
        curImgSrc = curImgSrc.replace("plus", "minus");
    } else if (curImgSrc.indexOf("minus") > -1) {
        curImgSrc = curImgSrc.replace("minus", "plus");
    }

    //curImgPath = curImgSrc.substring(0, curImgSrc.lastIndexOf("/")+1);
    //curImgName = curImgSrc.substring(curImgSrc.lastIndexOf("/")+1);
    //objImage.src = curImgPath + "icon_"+ newState +".gif";

    objImage.src = curImgSrc;
}

function changeLinkText(strElementID, strNewText) {
    strLinkElementID = strElementID + "-linktext";
    objLinkTextElement = document.getElementById(strLinkElementID);
    objLinkTextElement.firstChild.data = strNewText;
}


function openGiantOfficeWindow(objSelect, strPopUpUrl) {
    var objSelectedOption = objSelect.options[objSelect.selectedIndex];
    var strSelectedValue = objSelectedOption.value;

    if (strSelectedValue != "") {
        strPopUpUrl = strPopUpUrl + "?id=" + strSelectedValue;
        openPopUpWindow(strPopUpUrl);
    }

}

function openPopUpWindow(strPopUpUrl) {
    var MyWnd = window.open(strPopUpUrl, 'GiantBicycles', 'width=350,height=350,resizable=yes,scrollbars=yes,location=yes,menubar=no,toolbar=no,location=0,status=yes');
    MyWnd.focus();
}

function openWhereToGetItWindow(strPopUpUrl) {
    var MyWnd = window.open(strPopUpUrl, 'GiantBicycles', 'width=740,height=670,resizable=yes,scrollbars=yes,location=yes,menubar=no,toolbar=no,location=0,status=yes');
    MyWnd.focus();
}

function openInvodoWindow(strPopUpUrl) {
    var MyWnd = window.open(strPopUpUrl, 'GiantBicyclesInvodo', 'width=770,height=515,resizable=no,scrollbars=no,location=no,menubar=no,toolbar=no,location=0');
    MyWnd.focus();
}

function openDebugWindow(strPopUpUrl) {
    var MyWnd = window.open(strPopUpUrl, 'GiantBicyclesInvodo', 'width=770,height=515,resizable=no,scrollbars=1,location=no,menubar=no,toolbar=no,location=0');
    MyWnd.focus();
}


function setImage(strElementID, newImage) {
    objImage = document.getElementById(strElementID);
    curImgSrc = "" + objImage.src;
    curImgPath = curImgSrc.substring(0, curImgSrc.lastIndexOf("/") + 1);
    curImgPath = curImgPath + newImage;
    objImage.src = curImgPath;
}

function boxBorderHoverOn(objDiv) {
    objDiv.style.border = "1px solid #000000";
}

function boxBorderHoverOff(objDiv) {
    objDiv.style.border = "1px solid #CCCCCC";
}

function setImageTitle(objImageThumb) {
    titleOfThumb = objImageThumb.title;

    objImage = document.mainimage;
    objImage.title = titleOfThumb;
}

function setCaption(objImageThumb) {
    titleOfThumb = objImageThumb.title;

    objCaptionDiv = document.getElementById("caption");

    objCaptionDiv.innerHTML = titleOfThumb;

    //document.captionForm.caption.value = titleOfThumb;
}


function showToolTip(evt, nr, objArea) {
    //get element
    strElementID = "rollover_text_" + nr;
    objElement = document.getElementById(strElementID);
    objElement.style.top = "2000px";

    // position
    var dom = (document.getElementById) ? true : false;
    var ns5 = (!document.all && dom || window.opera) ? true : false;
    var ie5 = ((navigator.userAgent.indexOf("MSIE") > -1) && dom) ? true : false;
    var ie4 = (document.all && !dom) ? true : false;
    var nodyn = (!ns5 && !ie4 && !ie5 && !dom) ? true : false;


    standardbody = (document.compatMode == "CSS1Compat") ? document.documentElement : document.body //create reference to common "body" across doctypes
    mouseX = (ns5) ? evt.pageX : window.event.clientX + standardbody.scrollLeft;
    mouseY = (ns5) ? evt.pageY : window.event.clientY + standardbody.scrollTop;

    //mouseX = (ns5)? evt.pageX: window.event.clientX + standardbody.scrollLeft;
    //mouseY = (ns5)? evt.pageY: window.event.clientY + standardbody.scrollTop;

    // switch on
    showElement(strElementID);

    var newX = mouseX + 20;
    var newY = mouseY;
    //var newY = mouseY - objElement.offsetHeight;

    // place element
    objElement.style.position = "absolute";
    objElement.style.left = newX + "px";
    objElement.style.top = newY + "px";


}


function hideToolTip(nr) {
    strElementID = "rollover_text_" + nr;
    hideElement(strElementID);
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}


function pausecomp(millis) {
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while (curDate - date < millis);
}





function ensureInput(objForm, strFieldName, strLabelName) {
    strValue = getValueByFieldName(objForm, strFieldName);
    strLabel = getLabelValue(objForm, strLabelName);

    if (strValue == "") {
        setBackgroundColorToElement(objForm, strFieldName);
        return "> " + strLabel + "\n";
    } else {
        return "";
    }
}


function ensureEmailAddress(objForm, strFieldName, strLabelName) {
    strValue = getValueByFieldName(objForm, strFieldName);
    strLabel = getLabelValue(objForm, strLabelName);

    if (isValidEmailAddress(strValue) == false) {
        setBackgroundColorToElement(objForm, strFieldName);
        return "> " + strLabel + "\n";
    } else {
        return "";
    }
}

function ensureRadio(objForm, strFieldName, strLabelName) {
    var objFormField = objForm.elements[strFieldName];
    var intControlLength = objFormField.length;

    var strLabel = getLabelValue(objForm, strLabelName);
    var oneChecked = false;

    for (i = 0; i < intControlLength; i++) {
        if (objFormField[i].checked) {
            oneChecked = true;
            break;
        }
    }

    if (oneChecked == false) {
        return "> " + strLabel + "\n";
    } else {
        return "";
    }
}


function setBackgroundColorToElement(objForm, strFieldName) {
    //get object
    objElement = getElementByFieldName(objForm, strFieldName);

    if (objElement.type == "text") {
        objElement.className = "errorfield";
    }
}


function getElementByFieldName(objForm, strFieldName) {
    for (i = 0; i < objForm.elements.length; i++) {
        objElement = objForm.elements[i];
        if (objElement.name == strFieldName) {
            return objElement;
        }
    }
}


function getValueByFieldName(objForm, strFieldName) {
    strValue = "";

    for (i = 0; i < objForm.elements.length; i++) {
        objElement = objForm.elements[i];
        if (objElement.name == strFieldName) {
            strValue = objElement.value;
        }
    }

    return strValue;
}

function getLabelValue(objForm, strLabelName) {
    objElement = document.getElementById(strLabelName);

    strLabelValue = objElement.firstChild.data;

    return strLabelValue;
}


function isValidEmailAddress(strValue) {
    var objRegExp = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return objRegExp.test(strValue);
}


