
// Play different videos under /magasin/filmer/
function playVideo(file,image) {
  var flashvars = 'file='+file+'&image='+image;
  var s1 = new SWFObject("/o2www/flash/jwflvmediaplayer/player.swf","mediaplayer","470","318","9","#FFFFFF");
  s1.addParam("allowfullscreen","false");
  s1.addParam("allowscriptaccess","always");
  s1.addParam("flashvars","autostart=false&"+flashvars);
  s1.write("container1");
}

//Expand and collapse questions in kundeservice
function ShowHideElement(sender,objectID) {
  var object = document.getElementById(objectID);
  
  if (sender != null && object != null)
  {
    if (object.style.display == "none") object.style.display = "block";
    else object.style.display = "none";
  }
}

// Change tabs iphone-page
var tempE = "tab1";

function changeTab(e)
{
  if(tempE != null)
  {
    document.getElementById(tempE).className = "";
    document.getElementById(tempE + "_Content").style.display = "none";
  }

  document.getElementById(e).className = "current";
  document.getElementById(e + "_Content").style.display = "block";
  tempE = e;
}


// filter and sort functions on mobile-page
$(document).ready(function(){

  $('#initialSortingForm select').change(function() {
    $("#loadingDiv").show();
    $(".loadingImage").show();
    $('#initialSortingForm').submit();
  });

  $('#sortAndFilterForm select').change(function() {
    filterByBrandAndPlan();
  });
 
  $('.aboutLink').click (function() {
    return false;
  });
  $('.selectedPlan').click (function() {
    return false;
  });

  $('.aboutLink').hover(
    function() {
      $(this).find('.totalPriceInfo').show();
    },
    function() {
      $(this).find('.totalPriceInfo').hide();
    }
  );

});

jQuery(function(){
  $('.planInfoWrapper').live('mouseover', function(){
    $(this).children('div').show(); 
  });
  $('.planInfoWrapper').live('mouseout', function(){
    $(this).children('div').hide();
  });
});


// Sort the divs by price from low to high, either by total price or by phone price
function sortByPrice(whichPrice) {
  if (whichPrice == -1) {
    return;
  } 
  else {
    if (whichPrice == 'totalPrice') {
      var priceToSortBy = ".theTotalPrice";
    }
    if (whichPrice == 'phonePrice') {
      var priceToSortBy = ".thePrice";
    }
    $("div#phoneList>div").tsort(priceToSortBy, {order:"asc"});
  }
}

// Filter and sort phones based on the url
function _getUrlParam(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); 
  var regexS = "[\\?&]"+name+"=([^&#]*)"; 
  var regex = new RegExp( regexS ); 
  var results = regex.exec( window.location.href ); 
  if( results == null )    return ""; 
  else return results[1];
}

function initialFilterAndSort() {
  var brand = _getUrlParam('brand');
  var plan = _getUrlParam('plan');
  var sort = _getUrlParam('sort');

  if (brand) {
    $('#selectBrand').val(brand);
  }
  if (plan) {
    $('#selectPlan').val(plan);
  }
  if (sort) {
    $('#selectPriceSorting').val(sort);
  }
  filterByBrandAndPlan();
  $('select').resetSS();
}

// Adds the class "bottom" to divs on the last line on phone page
function addBottomClass() {
  $('.phone-list').each(function(){
    var max = $(this).find('div.phone.visible').length;
    var lines = Math.floor(max/3);
    var start = ((max%3) == 0)?(lines-1)*3:(lines*3);
    $(this).find('div.phone.visible:gt('+(start-1)+')').addClass('bottom');
  });
}

function findAndReplace(whichObject,whatToReplace,whereToPutIt) {
  var selectedPlan = $("#selectPlan").val();
  if ($("#selectBrand").val() == 'surfPhone' && selectedPlan == 'default') {
    selectedPlan = 'phone75MobilSurf';
  }
  var replaceThis = whichObject.find(whatToReplace+selectedPlan+':hidden');
  var replaceHere = whichObject.find(whereToPutIt);
  replaceHere.html(replaceThis.html());
}

function showOldPrices (object, plan, price, priceTarget, targetClass, insertBeforeWhat) {
  var oldPrice =  object.find(price+plan+':hidden');
  var oldPriceDiv = object.find(priceTarget);
  if ( oldPrice.length ) { // The selected plan has an old price to display
    if ( oldPriceDiv.length ) { //The wrapper for it exists, so just replace it
      findAndReplace(object,price,priceTarget);
    } else { //Wrapper doesn't exist, so let's create it
      var oldPriceContent = '<small class="'+targetClass+'">'+oldPrice.html()+'</small>';
      $(oldPriceContent).insertBefore(object.find(insertBeforeWhat));
    }
  } else if ( !oldPrice.length && oldPriceDiv.length ) { //Remove old price
    oldPriceDiv.remove();
  }
}

function filterByBrandAndPlan() {
  var selectedBrand = $("#selectBrand").val();
  var selectedPlan = $("#selectPlan").val();
  var selectedSorting = $("#selectPriceSorting").val();

  if (selectedBrand == 'surfPhone' && selectedPlan == 'default') {
    selectedPlan = 'phone75MobilSurf';
  }

  $(".phone").each(function() {
    //plan is available for this phone of selected brand, get the right prices and show it
    if ( ($(this).hasClass(selectedPlan) || selectedPlan == 'default') && ($(this).hasClass(selectedBrand) || selectedBrand == -1)) {

      //Replace discount in purple badge/Create it or remove it
      var discount = $(this).find('.phoneDiscount'+selectedPlan+':hidden'); //Hidden element that only excists if there's a discount
      var discountDiv = $(this).find('div.discount'); //The purple badge
      if ( discount.length ) { // The selected plan has a discount to display
        if ( discountDiv.length ){ //The wrapper for it exists, so just replace it
          findAndReplace($(this),".phoneDiscount",".thisPhoneDiscount");
        } else { //Wrapper doesn't exist, so let's create it
          var discountDivContent = '<div class="discount">Priskutt <br><span class="thisPhoneDiscount">'+discount.html()+'</span></div>';
          $(this).find('.image').append(discountDivContent);
        }
      } else if (!discount.length && discountDiv.length ) { //Remove the purple badge if there's no discount
        discountDiv.remove();
      }
      //Replace/create or remove old price

      showOldPrices($(this),selectedPlan,".oldPrice",".thisOldPrice","thisOldPrice",".price");
      showOldPrices($(this),selectedPlan,".oldOldPrice",".thisOldOldPrice","thisOldOldPrice",".thisOldPrice");
      
      // Change the prices and text in popup
      findAndReplace($(this),".planNameOnly",".thisPlanNameOnly"); //Price for phone
      findAndReplace($(this),".price",".thePrice"); //Price for phone
      findAndReplace($(this),".totalPrice",".theTotalPrice"); //Total price
      findAndReplace($(this),".planExtraInfo",".thisPlanExtraInfo"); //Extra info, i.e. mobilsurf
      findAndReplace($(this),".bubbleBody",".bubbleBody:hidden"); //Total price info popup
      findAndReplace($(this),".planInfoBubble",".planInfoBubble:hidden"); //Plan prices popup      

      // Replace URL
      var thisPlanOrderUrl = $(this).find('".phoneUrl'+selectedPlan+':hidden"').text();
      $(this).find(".phoneOrderLink").attr("href", thisPlanOrderUrl);
      $(this).click(function() {
        window.location = thisPlanOrderUrl;
      });

      // Show phone
      $(this).fadeIn('400');       
      $(this).addClass('visible');
    }

    //phone doesn't have selected brand or plan is not available, so let's hide it!
    else {
      $(this).removeClass('visible');
      $(this).hide();
    }
    $(this).removeClass('bottom');
  });
  showOrHideFlashBanner(selectedBrand, selectedPlan);
  sortByPrice(selectedSorting);
  addBottomClass();
}

// Show flashbanner if surfetelefoner or plan with mobilsurf is selected
function showOrHideFlashBanner(brand, plan) {
  if (brand == 'surfPhone' || plan == 'phone75MobilSurf' || plan == 'phone175MobilSurf') {
    $("#cellFlashBanner").show();
  } else {
    $("#cellFlashBanner").hide();
  }
}

// Show newsletter signup

(function($){
 $('a#newsletter-signup').click(function() {
   $('#signup-form').show('fast');
   return false;
 });
})(jQuery);


//Show different combi plan prices 

function showCombiPrices() {
  var planFromUrl = _getUrlParam('plan');
  
  if(planFromUrl) {
    var currentPlan = planFromUrl;
  }
  else {
    var currentPlan = "small";
  }
  showPrices(currentPlan);
}
  

function showPrices(selectedOpt) {
  if (selectedOpt.value) {
    var currentPlan = selectedOpt.value;
  }
  else {
    var currentPlan = selectedOpt;
  }
  $(".combiPrices").each(function() {
    if ($(this).attr("id") == currentPlan+"_content") {
      $(this).show();
    }
    else {
      $(this).hide();
    }
    $("#selectBrand").val(currentPlan);
    $('#selectBrand').resetSS();
  });

  //if(currentPlan != null)
  //{
  //  document.getElementById(currentPlan + "_content").style.display = "none";
  //}
  //document.getElementById(size + "_content").style.display = "block";
  //currentPlan = size;
}

// Banner slider on frontpage

$(document).ready(function(){	
  $("#slider").easySlider({
    loop: true,
    autoplayDuration: 5000, 
    pauseable: true,
    restartDuration: 500,
    easing: 'linear'
  });
});	

// Mobile flash
var FlashBanner = $.flash.create ({
  swf: '/flash/Carousel.swf?src=/o2/Shop-Product/getXMLForFlashBanner',
  width: 956,
  height: 295,
  hasVersion: '9.0.115',
  params: {
    wmode: "transparent"
  }
});


if ($.flash.hasVersion('9.0.115')) {
  $('#flashBannerCarousel').html(FlashBanner);
}
