// no conflicts blz
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){

    jQuery('.productInfo img[alt=""]').each(function() {
        var prodName = jQuery('.productImage img').attr('alt');
        jQuery(this).attr('alt', prodName).attr('title', prodName);
    });

    jQuery(".error_message").each(function () {
       jQuery(this).html(jQuery(this).html().replace(/Please enter a valid email address for /g, 'Anna arvo kentälle '));
       jQuery(this).html(jQuery(this).html().replace(/Please enter a value for /g, 'Anna arvo kentälle '));
    });

    jQuery('#cntnt01fbrp_submit').val('Lähetä');

      var pathname = window.location.pathname;

      if(pathname == '/hankintaturva/yhteydenotto/') {  

         jQuery('input[type="checkbox"]').ezMark();

         jQuery('input[type="radio"]').ezMark();
      }

    // Some vars for development and testing
    var dev 	= false;
    var tld 	= jQuery('.tld-ext').text();
    // scroll teh news (if present)
    var newsTicker = jQuery("#newsArea").length;
    if (newsTicker > 0) {
        var scrolloptions = {
            newsList: "#newsTickerList",
            startDelay: 10,
            placeHolder1: ""
        }
        jQuery().newsTicker(scrolloptions);        
    }
   // dealer search (redirect)
   jQuery("input#dealerSearchSubmit").click(function() {
	var url = window.location.href.split("http://")[1];
	var siteLang = url.split("/")[1];
	var urlCheck = url.split(".fi/")[1];
	
	if(urlCheck == undefined) {
	    urlCheck = url.split(".se/")[1];
	}

	
	var siteEng = urlCheck.split("/")[1];   
	
	//console.log(siteEng);
	
    var searchAddress = jQuery("input#dealerSearch").val();
     // Which way to go?
     switch(siteLang) {
         case 'fi':
		     if (siteEng == "english") {
				window.location = "/en/jaelleenmyyjaet/hae-jaelleenmyyjae-kartalta/#"+escape(searchAddress);
				break;				
			 }
			 else {
				window.location = "/fi/jaelleenmyyjaet/hae-jaelleenmyyjae-kartalta/#"+escape(searchAddress);
				break;
			 }
      	 case 'se':
			 //window.location = "/se/jaelleenmyyjaet/hae-jaelleenmyyjae-kartalta/#"+escape(searchAddress);
			 window.location = "/se/aterfoersaeljareaere/soek-aterfoersaeljare/#"+escape(searchAddress);
			 break;
         case 'no':
			 window.location = "/no/jaelleenmyyjaet/hae-jaelleenmyyjae-kartalta/#"+escape(searchAddress);
			 break;
      }        
    });
    // products page
    jQuery("body.products #catselector a").toggle(function() {
        jQuery("#cats1").hide();
        jQuery("#cats2").show();
        return false;
    }, function() {
        jQuery("#cats2").hide();
        jQuery("#cats1").show();
        return false;
    });

    /* icons for product attachment links */
    if(jQuery('table.technicalData')) {
        // Get all links
        var links = jQuery('table.technicalData a');
        jQuery.each(links, function() {
            var href = jQuery(this).attr('href');
            var ext = href.split(".").reverse();
            // Add extension as a class to image div
            jQuery(this).prev().addClass(ext[0].toLowerCase());            
        });
    }
    // region
    jQuery("select#region").change(function() {
        var reg = jQuery("#region option:selected").val();
        if (reg == "fi") {
            window.location = (dev == true) ? "http://pg.restate.fi" : "http://www.scanoffice.fi";
        } else if (reg == "se") {
            window.location = (dev == true) ? "http://scanoffice.testink.net" : "http://www.scanoffice.se";
        } else if (reg == "no") {
            window.location = (dev == true) ? "http://scanoffice.helsky.com" : "http://www.scanofficenorge.com";
        }
    });
    
    /** 
    * doSearch | perform city search to userlisting 
    * param: <string> name of requested city
    * todo: complete multilingual messaging
    **/
    function doSearch(city) 
    {
	// unescape urlencoding
	city = unescape(city);
	// Add search value to input field
	jQuery('#DS_company_city').val(city);
        // Grab the search term
        if(city.length > 2) {
            // Search term
            var search  = jQuery.trim(city.toLowerCase());
            // matches
            var match = 0;
            // iterate all rows
            jQuery('.userdirectory_oneuser').each( function(i) {
                // value to match against
                var val = jQuery.trim(jQuery(this).find('.locality').text());                
                // Find matches and show them and hide mismatches
                if( beginsWith(search, val) == true ) {
                    jQuery(this).show();
                    match++;
                } else {
                    jQuery(this).hide();
                }
            });
            // Display listing
            jQuery('div.listing').show();
            // Show message if none found
            if(match == 0) {

		switch(tld){
		    case 'fi':
			jQuery('.message').html('Ei lÃ¶ytynyt haulla: ' + search).show();
			break;
		    case 'se':
		    case 'com':
			jQuery('.message').html('Not found: ' + search).show();
			break;
		}
            } else {
        	switch(tld) {
        	
        	    case 'fi':
        		jQuery('.message').html('LÃ¶ytyi ' + match + ' osumaa.');
        		break;
        	    case 'se':
        	    case 'com':
        		jQuery('.message').html('Found ' + match + ' matches.')
            	}
            }
            
        }        

    }
    
    // If hash found in url, append search term to input and perform search automagically
    var hash = window.location.hash;
    if(hash.length > 0 && jQuery('.DS')) {
	// remove the # sign
	hash = hash.substr(1);
	doSearch(hash);
    }    
    // dealer inline LITE-search for extranet and public pages
    jQuery('#DS_company_city').bind('change keyup', function() {
        // Grab the search term
        if(jQuery(this).val().length > 2) {
            // Search term
            var search  = jQuery.trim(jQuery(this).val().toLowerCase());            
            doSearch(search);
        }        
    });
    // hide language-text from header
    jQuery("#langLinks span:contains('LANGUAGE:')").remove();
    
    /* Email links, substitute ^ to @ */
    if(jQuery('.DS')) {
	// replace ^ with @
	var links = jQuery('.DS .email');
	jQuery.each(links, function(){
	    var address	= jQuery(this).text().replace('^','@');
	    var markUp 	= '<a class="mailtoLink" href="mailto:'+address+'">'+address+'</a>';
	    jQuery(this).html(markUp);
	});	
    }
    
    /**
    * Extranet stuff starts here
    **/
    // Remove form values from delivery address
    if(jQuery('body.extranet')) {
	var hidden = jQuery('body.extranet .orderForm .hidden input');
	jQuery.each( hidden, function() {
	    jQuery(this).val('');
	});
	
	// show loginform
	jQuery("#sitemapLink").toggle(function() {
	    jQuery("#extranetLoginForm").show();
	    return false;
	}, function() {
	    jQuery("#extranetLoginForm").hide();
	    return false;
	});
	
	/*
	jQuery('#breadcrumbs a').each(function(i) 
	{
	    if(i <= 1) jQuery(this).remove();
	    else jQuery(this).after(' > ');
	});
        */
	
	
    }
    
    // Populate form fields with hidden vars
    if(jQuery('#billingUserinfo')) {
	// populate fields
	var company 	= jQuery(this).find('.company_name').text();
	var address	= jQuery(this).find('.company_street_address').text();
	var city	= jQuery(this).find('.company_city').text();
	var postcode	= jQuery(this).find('.company_postcode').text();
	var phone	= jQuery(this).find('.company_telephone').text();
	
	jQuery('.orderForm .company input').val(company);
	jQuery('.orderForm .address1 input').val(address);
	jQuery('.orderForm .city input').val(city);
	jQuery('.orderForm .postal input').val(postcode);
	jQuery('.orderForm .phone input').val(phone);
    
    
    }
    
    
});
// Used to check if a given search string begins with a target strings beginning
function beginsWith(search, target) {
    //     
    searchLen = search.length;
    search = search.substring(searchLen,0).toLowerCase();
    target = target.substring(searchLen,0).toLowerCase();
    
    if(target == search) {
        return true;
    } else {
        return false;
    }
}

// font magic
Cufon.replace('h1');
Cufon.replace('h2');
Cufon.replace('h3');
Cufon.replace('h4');
Cufon.replace('h5');
Cufon.replace('h6');

var Browser = {
  Version: function() {
    var version = 999; // we assume a sane browser
    if (navigator.appVersion.indexOf("MSIE") != -1)
      // bah, IE again, lets downgrade version number
      version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    return version;
  }
}
if (Browser.Version() < 7) {
    var domaini = window.location.host.split(".");
    if (domaini[2] == "net" || domaini[2] == "se") {
        // svenski alert for ie
        alert("Vänligen använd uppdaterad webbläsare, min. Internet Explorer version 7 eller till exempel senaste version av Mozilla Firefox");
    } else if (domaini[2] == "com") {
        // norski alert for ie
        alert("Vänligen använd uppdaterad webbläsare, min. Internet Explorer version 7 eller till exempel senaste version av Mozilla Firefox");
    } else {
        // finski alert for ie
        alert("Käytäthän sivustollamme uudehkoa selainta, minimissään Internet Explorerin versiota 7 tai esimerkiksi Firefoxin uusinta versiota.");
    }
}

