
// 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;
  });

  $('.withPopup').live('mouseover mouseout', function(event) {
    var thePopup = $(this).children('.popupBubble');
    var facebookIframe = $(this).parents("div.phone").find(".fbLikeBox");
  
    if (event.type == 'mouseover') {
      thePopup.show();
      facebookIframe.hide();
    } else {
      thePopup.hide();
      facebookIframe.show();
    }
  });

});


// 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+":visible", {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() {
  
	$('select').sSelect();
	
  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();
  setSelectClasses();
}

// Adds the class "bottom" to divs on the last line on phone page
function addBottomClass() {
  $('.phone-list').each(function(){
    var $this = $(this); //Speed things up
    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();
  var replaceThis = whichObject.find(whatToReplace+selectedPlan+':hidden');
  var replaceHere = whichObject.find(whereToPutIt);
  replaceHere.html(replaceThis.html());
}

function setSelectClasses() {
  $(".sorting select").each(function() {
    var selectEl = $(this);
    var selectValue = selectEl.val();
    var selectDiv = selectEl.next(".newListSelected");

    if (selectValue == -1 || selectValue == 'default') {
      selectDiv.removeClass("hasValue");
    }
    else {
      selectDiv.addClass("hasValue");
    }
  });
}

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

  $(".phone").each(function() {
    var $this = $(this); //Speed things up
    //plan is available for this phone of selected brand, replace text and prices and show it!
    if ( ($this.hasClass(selectedPlan) || selectedPlan == 'default') && ($this.hasClass(selectedBrand) || selectedBrand == -1)) {

      // Change the phone plan related content
      findAndReplace($this,".phoneInfo",".thisPhoneInfo");

      // Add click event for entire phone div
      /*var thisPlanOrderUrl = $this.find('.phoneOrderLink').attr("href");
      $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');
  });
  sortByPrice(selectedSorting);
  //addBottomClass();
  setSelectClasses();
  paginate();
  var History = window.History;
  if ( History.enabled ) {
    History.pushState(null, "djuice - mobil", "?brand="+selectedBrand+"&plan="+selectedPlan+"&sort="+selectedSorting);
  }
}

// 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();
  });
}


function paginate(show_per_page) { /* Adapted from this: http://web.enavu.com/tutorials/making-a-jquery-pagination-system/ */
  var visible_phones = $("#phoneList .visible").length; // Since we already hid some phones, count only the ones that are visible
  var show_per_page = show_per_page ? show_per_page : 6; //Number of phones to show
  var number_of_pages = Math.ceil(visible_phones/show_per_page);

	$('#current_page').val(0);
	$('#show_per_page').val(show_per_page);

  var navigation_html = "";

	var current_link = 0;
	while (number_of_pages > current_link) {
		navigation_html += '<a class="pageLink" href="javascript:go_to_page(' + current_link +')" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
		current_link++;
	}
	
	navigation_html += '<a class="previousLink" href="javascript:previous();">Forrige</a>';
	navigation_html += '<a class="nextLink" href="javascript:next();">Neste</a>';
	navigation_html += '<a href="javascript:show_all();">Se alle</a>';

	$('.pageNavigation').html(navigation_html);

	//add active_page class to the first page link
	$('.pageNavigation .pageLink:first-child').addClass('active_page');

	//hide all the elements inside content div
	$('#phoneList').children().css('display', 'none');

	//and show the first n (show_per_page) elements
	$('#phoneList').children(".visible").slice(0, show_per_page).fadeIn("fast");
}


function previous(){
	new_page = parseInt($('#current_page').val()) - 1;
	//if there is an item before the current active link run the function
	if($('.active_page').prev('.pageLink').length){
		go_to_page(new_page);
	}
}

function next(){
	new_page = parseInt($('#current_page').val()) + 1;
	//if there is an item after the current active link run the function
	if($('.active_page').next('.pageLink').length){
		go_to_page(new_page);
	}
}

function go_to_page(page_num){
	//get the number of items shown per page
	var show_per_page = parseInt($('#show_per_page').val());

	//get the element number where to start the slice from
	start_from = page_num * show_per_page;

	//get the element number where to end the slice
	end_on = start_from + show_per_page;

	//hide all children elements of content div, get specific items and show them
	$('#phoneList').children(".visible").css('display', 'none').slice(start_from, end_on).css('display', 'block');

	/*get the page link that has longdesc attribute of the current page and add active_page class to it
	and remove that class from previously active page link*/
	$('.pageLink[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');

	//update the current page input field
	$('#current_page').val(page_num);
}

function show_all() {
  var show_per_page = $("#phoneList .visible").length;
  go_to_page(0);
  paginate(show_per_page);
}

// 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);
}
