var geocoder, map;

function initMap() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(19.0018, 72.8190);
    var myOptions = {
        zoom : 13,
        center : latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("dealer_map"), myOptions);
}

function markDealers(locations){
    var count = -1, address;
    //alert(locations.length);
    for (count = 0; count < locations.length; count=count+1) {
        address = '';
        if (locations[count].address != ''){
            address = locations[count].address;
        }
        if (locations[count].city != ''){
            if (address != '') {
                address = address + " , " + locations[count].city;
            } else {
                address = locations[count].city;
            }
        }
        if (locations[count].state != ''){
            if (address != '') {
                address = address + " , " + locations[count].state;
            } else {
                address = locations[count].state;
            }
        }
        if (locations[count].country != ''){
            if (address != '') {
                address = address + " , " + locations[count].country;
            } else {
                address = locations[count].country;
            }
        }
        locateDealer(address, true, locations[count].name, locations[count].image);
    }
}

function locateDealer(address, is_center, dealerName, image) {
    //alert("address = "+address);
    geocoder.geocode({
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (is_center) {
                map.setCenter(results[0].geometry.location);
            }
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                title : dealerName
            });
        } else {
    //alert("Location not found for " + address);
    }
    });
}

function dealer(name,address,city,state,country,image)
{
    this.name = name;
    this.address = address;
    this.city = city;
    this.state = state;
    this.country = country;
    this.image =image;
}
//------------------------EVENTS----------------------------------------------
var selectedIds;
function getSelectedEvents(selectedids) {
    selectedIds = selectedids;
    var request = new AjaxRequest(url, addSelectedEvents);
    request.setParameter("selectedids", selectedids);
    request.submit();
}

function addSelectedEvents(xml, text){
    //    alert("addSelectedEvents = "+xml);
    var count=xml.getElementsByTagName("event-and-gallery").length;
    var event = xml.getElementsByTagName("event-and-gallery");
    var selectedEvents = document.getElementById("selected-events");
    var urlprefix = document.getElementById("urlprefix").value;
    var eventurl = document.getElementById("event-details-url").value;
    var selectedEventHtml = "";
    for(var eventsIndex=0;eventsIndex<count;eventsIndex++){
        var id = event[eventsIndex].getElementsByTagName('ID')[0].firstChild.nodeValue;
        var flag = event[eventsIndex].getElementsByTagName('FLAG_IMAGE_PATH')[0].firstChild.nodeValue;
        var title = event[eventsIndex].getElementsByTagName('TITLE')[0].firstChild.nodeValue;
        var summary = event[eventsIndex].getElementsByTagName('SUMMARY')[0].firstChild.nodeValue;
        if(flag != '' && title !=''){
            flag = '<div class="flag_title"><div class="flag_pos"> <div class="icon-space"><img src="'+(urlprefix+flag)+'" alt="" width="16" height="16" hspace="0" vspace="0" border="0" align="right" /></div></div></div>'
            title = '<div class="event_title">'+title+'</div><div class="clear"></div>';
        }
        if(summary !=''){
            summary ='<div class="flag_content">'+summary+'</div>';
        }
        var gallery = event[eventsIndex].getElementsByTagName('image');
        var galleryLength = event[eventsIndex].getElementsByTagName('image').length;
        if(galleryLength > 0){
            if(galleryLength > 6){
                galleryLength = 6;
            }
            var galleryHtml = '<div class="flag_content">|gallery|</div>';
            var images = '';
            for(var galleryIndex=0;galleryIndex<galleryLength;galleryIndex++){
                var image = gallery[galleryIndex].getElementsByTagName('THUMBNAIL_IMAGE_PATH')[0].firstChild.nodeValue;
                images+='<div class="gallery_box"><img src="'+urlprefix+image+'" width="98" height="46" /></div>';
            }
            summary += galleryHtml.replace("|gallery|", images);
        }
        var galleryLink = '<div class="view_full_gall"><a href="'+eventurl+selectedIds+"/"+id+'">View Details</a></div><div class="clear"></div>';
        selectedEventHtml+='<div class="box_content">'+flag+title+summary+galleryLink+'</div>';
    }
    selectedEvents.innerHTML = selectedEventHtml;
}

//----------------------------------------------------------------------

function populateCities(id) {
    var param = "state";
    var request = new AjaxRequest(url, handleResponse);
    request.setParameter(param, id);
    request.submit();
}

function handleResponse(xmlDoc, text) {
    var x=xmlDoc.getElementsByTagName("node")[0];
    var count=xmlDoc.getElementsByTagName("node").length;
    document.getElementById('city_id').innerHTML = "";
    addDefaultOption();
    for(var i=0;i<count;i++){
        var elOptNew = document.createElement('option');
        elOptNew.text = xmlDoc.getElementsByTagName("node")[i].getElementsByTagName('name')[0].firstChild.nodeValue;
        elOptNew.value = xmlDoc.getElementsByTagName("node")[i].getElementsByTagName('id')[0].firstChild.nodeValue;
        var elSel=document.getElementById('city_id');

        try {
            elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
        }
        catch(ex) {
            elSel.add(elOptNew); // IE only
        }
    }
}

function addDefaultOption() {
    var eleOptNew = document.createElement('option');
    eleOptNew.text = "Select City";
    eleOptNew.value = "0";
    var elSel=document.getElementById('city_id');

    try {
        elSel.add(eleOptNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
        elSel.add(eleOptNew); // IE only
    }
}

function findDealers(caseId) {
    //alert("findDealers() = "+caseId);
    var request = new AjaxRequest(url, findDealersResponse);
    if(caseId == 1){
        var postcode = document.getElementById("postcode").value;
        //alert("PostCode = "+postcode);
        request.setParameter("postcode", postcode);
    }else if(caseId == 2){
        var stateId = document.getElementById("state_id").value;
        var cityId = document.getElementById("city_id").value;
        //alert("Values = "+stateId+"  "+cityId);
        request.setParameter("state", stateId);
        request.setParameter("city", cityId);
    }
    request.submit();
}

function findDealersResponse(xmlDoc, text) {
    var noOfDealer = xmlDoc.getElementsByTagName("node").length;
    //alert("noOfDealer = "+noOfDealer);
    var dealersAddressContainer = document.getElementById("dealer_add");
    if(noOfDealer > 0){
        var dealerDetails = "<div id='dealer_name'>";
        var locations = [];
        for(var dealerIndex=0;dealerIndex < noOfDealer; dealerIndex++){
            var dealerId = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('id')[0].firstChild.nodeValue;
            var dealerName = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('name')[0].firstChild.nodeValue;
            var dealerAddress = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('address')[0].firstChild.nodeValue;
            var dealerCountry = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('country')[0].firstChild.nodeValue;
            var dealerState = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('state')[0].firstChild.nodeValue;
            var dealerCity = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('city')[0].firstChild.nodeValue;
            var dealerPostcode = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('postcode')[0].firstChild.nodeValue;
            var dealerTelno = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('telno')[0].firstChild.nodeValue;
            var dealerEmail = xmlDoc.getElementsByTagName("node")[dealerIndex].getElementsByTagName('email')[0].firstChild.nodeValue;

            locations.push(new dealer(dealerName,dealerAddress,dealerCity,dealerState,dealerCountry,"img/go.jpg"));

            dealerDetails += '<div class="dealer_details">';
            //            if(dealerImageSrc != ''){
            //                dealerDetails += '<img height="117" width="219" src="'+dealerImageSrc+'"/>';
            //            }
            if(dealerName !=''){
                dealerDetails += '<p class="name">'+dealerName+'</p>';
            }
            if(dealerAddress != ''){
                dealerDetails += '<p >'+dealerAddress+'</p>';
            }
            dealerDetails += '<p>'+dealerCity+' - '+dealerPostcode+'</p>';
            dealerDetails += '<p>'+dealerState+', '+dealerCountry+'</p>';
            if(dealerTelno != ''){
                dealerDetails +='<p> Tel : '+dealerTelno+'</p>';
            }
            if(dealerEmail != ''){
                dealerDetails += '<p> Email : '+dealerEmail+'</p>';
            }
            dealerDetails += '</div>';
        }
        dealerDetails += '</div>';
        dealerDetails += '<div id="dealer_map"></div><div style="clear:both"></div>';
        dealersAddressContainer.innerHTML = dealerDetails;
        initMap();
        markDealers(locations);
    }else{
        dealersAddressContainer.innerHTML = "<div id='dealer_name'><strong>No Dealer Found.</strong></div>";
    }
}

function submit(formname){
    var form = document.getElementById(formname);
    form.submit();
}

function setLocale(id){
    var newLocale = document.getElementById("newlocale");
    newLocale.value = id;
    alert(newLocale.value);
    submit("localeform");
}
function setEventYear(id){
    var year = document.getElementById("eventyear");
    year.value = id;
    //    alert(year.value);
    submit("eventform");
}

function addParameter(value){
    var searchString = "download_brochure";
    if(value!="Select Product"){
        var successurl = document.getElementById("successurl").value;
        var index = successurl.indexOf(searchString, 0);
        var url = successurl.substr(0, (index + searchString.length));
        value = url + "&dcr="+ value.toLowerCase().replace(" ", "-","gi");
        document.getElementById("successurl").value = value;
    //        alert("URL = "+document.getElementById("successurl").value);
    }
}

function addValidator(){
    $("#contactusform").validate({
        submitHandler:function(form){
            $.ajax({
                type:"POST",
                url:$(form).attr("action"),
                data:$(form).serialize(),
                success:function(d){
                    var c=$(d).find("status").text();
                    $(form).hide();
                    $("#"+c).show();
                }
            })
        }
    });

    var tablename = document.getElementById("tablename").value;
    if(tablename == 'download_brochure'){
        $("#product").change(function(){
            var value = $(this).val();
            if(value != 'Select Product'){
                var product = document.getElementById(value).value;
                var urlprefix = document.getElementById("urlprefix").value;
                var pdfUrl = urlprefix+product;
                //alert("Name = " + tablename+" :::: Product = "+pdfUrl);
                var ahtml = "<strong><a href='"+pdfUrl.replace("//resources", "/resources")+"'><img hspace='10' height='32' width='32' align='middle' alt='Download Brochure' src='"+urlprefix+"resources/images/layout/icon_pdf.png'/>Download Brochure</a></strong>";
                $("#ebrochure").html(ahtml);
            }
        });
    }

    //select all the a tag with name equal to modal
    $('a[name=modal]').click(function(event) {
        //Cancel the link behavior
        event.preventDefault();

        //Get the A tag
        var id = $(this).attr('href');

        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set heigth and width to mask to fill up the whole screen
        $('#mask').css({
            'width':maskWidth,
            'height':maskHeight
        });

        //transition effect
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow",0.8);

        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);

        //transition effect
        $(id).fadeIn(2000);

    });

    //if close button is clicked
    $('.window .close').click(function (event) {
        //Cancel the link behavior
        event.preventDefault();

        $('#mask').hide();
        $('.window').hide();
    });

    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });
}



function registerTab(count){

    var heading = $("#pageHeading").text();
    $("ul#tab li").click(function(){
        var number=$(this).index();
        $(".sec").hide().eq(number).fadeIn();
        $("ul#tab li").not(this).removeClass("active").addClass("unactive");
        $("ul#tab li").not(this).find("a").removeClass("activeLink").addClass("unactiveLink");
        $(this).removeClass("unactive").addClass("active");
        $(this).find("a").removeClass("unactiveLink").addClass("activeLink");
        $(".featureContent").hide().eq(number).fadeIn();
        $("#pageHeading").replaceWith("<div id='pageHeading'><h1>"+heading+" - "+$(this).find("a").text()+"</h1></div>");
    });

    $(".sec").not(":first").hide();
    $("ul#tab li:first").addClass("active");
    $("ul#tab li:first").find("a").addClass("activeLink");
    $("ul#tab li").not(":first").addClass("unactive");
    $("ul#tab li").not(":first").find("a").removeClass("activeLink").addClass("unactiveLink");
    $(".featureContent").not(":first").hide();
    $("#pageHeading").replaceWith("<div id='pageHeading'><h1>"+heading+" - "+$("ul#tab li:first").text()+"</h1></div>");

    for(var slide=1;slide<=count;slide++){
        registerSlideshow("-"+slide);
    }
}

function registerSlideshow(scount){
    //        alert("Scount = "+scount);
    var width=0;
    var frameNo=3;
    var imgWidth=$("#imgWrap-1 img:first").width();
    var conatinerWidth=(imgWidth+20)*frameNo; //20 here is the padding left 10px and right 10px
    var wrapperWidth=conatinerWidth+(18*2);
    var leftPos=(imgWidth+20);
    var iniLeft=0;
    //assign the width to the containers
    // $("#imgWrapper"+scount).css("width",wrapperWidth);
    $("#imgContainer"+scount).css("width",conatinerWidth);
    $("#imgWrap"+scount+" img").each(function(){
        width+=imgWidth+20;   //Here 20 is pading left and right of the image
    });

    $("#imgWrap"+scount).css("width",width);

    //Click function
    $("#prev"+scount).click(function(){
        if(iniLeft>=width)
            iniLeft=(iniLeft)-(imgWidth+20);
        if(iniLeft>=leftPos)
        {
            iniLeft-=leftPos;
            $("#imgWrap"+scount).animate({
                left:-iniLeft
            },800);
        }
    });

    $("#next"+scount).click(function(){
        if(iniLeft<=0)
            iniLeft=0;
        if(iniLeft<width-(leftPos*frameNo))
        {
            iniLeft+=leftPos;
            $("#imgWrap"+scount).animate({
                left:-iniLeft
            },800);
        }
    });

    var imgCount=$("#imgWrap"+scount+" img").length;
    $("#imgWrap"+scount+" img").click(function(){
        $("#imgWrap"+scount+" img").not(this).removeClass("activeimg");
        $(this).addClass("activeimg");
        var imgNo=($(this.parentNode).index())+1;
        $("#imgSelect"+scount).html(imgNo+"/"+imgCount);
        // $(".featureContent"+scount).hide().eq(ImgNo-1).fadeIn();
        $("#sliderContent"+scount+" .sliderContent").hide().eq(imgNo-1).fadeIn();
    });

    $("#imgWrap"+scount+" img:first").addClass("activeimg");
    $("#imgSelect"+scount).html("1/"+imgCount);
    //$(".featureContent"+scount).not(":first").hide();
    $("#sliderContent"+scount+" .sliderContent").not(":first").hide();
}

/** Home Page **/
function loadHome() {

    $('#slideshow').cycle({
        fx: 'fade',
        timeout: 3000,
        pause : 1
    });

    $('.homevideo').click(function() {
        $('#slideshow').cycle('pause');
        $('#slideshow').hide();
        $('#slideshadow').hide();
        $('#video').css('display','block');
        $('.backtopage').css('display','block');
    });

    $('.backtopage').click(function(){
        $('.backtopage').hide();
        $('#video').hide();
        $('#video').html('');
        $('#slideshow').show();
        $('#slideshadow').show();
        $('#slideshow').cycle('resume');
    });


    $(".vdoImg").not(":first").hide();
    $(".vdoContent").not(":first").hide();
    $(".vdoIcon").not(":first").addClass("unactiveicon");
    $(".vdoIcon:first").addClass("activeicon");

    $(".vdoIcon").click(function(){
        var numb=$(this).index();
        $(".vdoImg").hide().eq(numb).fadeIn();
        $(".vdoContent").hide().eq(numb).fadeIn();
        $(".vdoIcon").removeClass("activeicon").addClass("unactiveicon");
        $(".vdoIcon").eq(numb).removeClass("unactiveicon").addClass("activeicon");
    });

    $(".vdo").colorbox({
        iframe:true,
        innerWidth:680,
        innerHeight:400
    });

}

/** load video using external url directly to specified div **/

function loadPage(outputarea, external) {
    $(outputarea).load(external);
}

/** Update "src" of "img" Element **/
function showimage(element_id, image_path) {
    var element = document.getElementById(element_id);
    if (element != null) {
        element.src = image_path;
    }
}

