/*
	Site:		Denizen
	File:		/js/script.js
	Author:		vinay@artminister.com
	Version:  26-01-2010
	
*/


var Denizen = {
  loader:'<img src="/sites/all/themes/zen/denizen/images/loader-rectangle.gif" alt="Loading">',
  init:function(){
    
    // Define Curve
    
    $('.define').find('li').click(function(){
      var $li = $(this);
      $li.find('input[type="radio"]').attr('checked', true);      
      $li.siblings().removeClass("active");
      $li.addClass("active");
    });
    
    
    // Load Google Map
    
    if($('#Gmap').length) Denizen.locator();
    
    // Init Popups
    
    jQuery('a[rel*=popup]').click(function(e){
      var $this= $(this),
          pwidth = $this.attr("data-width")||400,
          pheight = $this.attr("data-height")||500,
          pleft = parseInt((screen.availWidth/2) - (pwidth/2)),
          ptop = parseInt((screen.availHeight/2) - (pheight/2));
          
      window.open(this.href,'win1','width='+pwidth+',height='+pheight+',menubar, resizable,left='+pleft+',top='+ptop+',screenX='+pleft+',screenY='+ptop);
      e.preventDefault();
    });
    
  },
  locator:function(){
    
    var _map = '#Gmap';
		var myLatLng = new google.maps.LatLng(38.222070303501155, 177.36328125); // Default Latlng
    DMap.init(_map, myLatLng, 2);
    
    // Add Click Handler to Address
    
    jQuery('.addressGoLeft a, .addressGoRight a').click(function(e){
      e.preventDefault();            
      DMap.placeMarkerfromLink($(this));
      
      jQuery('html,body').animate({
        scrollTop:0
      },500);
    });
    
  }
  
};


// Google Map Locator 

var infowindow,
    markersArray = [];
			
var DMap = {
  map: null,
	bounds: null,
	marker_store :'/sites/all/themes/zen/denizen/images/marker_grey.png',
	marker_main  :'/sites/all/themes/zen/denizen/images/marker_blue.png',
	marker_selected :'/sites/all/themes/zen/denizen/images/map-country-pointer.png'
};

DMap.init = function(selector, latLng, zoom) {
      //log(selector);
  var myOptions = {
    zoom:zoom,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl:true,
    mapTypeControlOptions:{
      position: google.maps.ControlPosition.TOP_LEFT
    },
    panControl: true,
    panControlOptions: {
      position: google.maps.ControlPosition.TOP_RIGHT
    },
    zoomControl: true,
    zoomControlOptions: {
      style: google.maps.ZoomControlStyle.LARGE,
      position: google.maps.ControlPosition.RIGHT_CENTER
    }
  };
  this.map = new google.maps.Map($(selector)[0], myOptions);
	this.bounds = new google.maps.LatLngBounds();
  //DMap.placeMarkers('inc/markers.xml');
  //google.maps.event.addListener(this.map, 'idle', DMap.showMarkers);
  
};

DMap.placeMarkers = function(filename) {
	$.get(filename, function(xml){
		$(xml).find("marker").each(function(){
			var name = $(this).find('name').text();
			var address = $(this).find('address').text();
			var tel = $(this).find('tel').text();
			var fax = $(this).find('fax').text();
			
			// create a new LatLng point for the marker
			var lat = $(this).attr('lat');
			var lng = $(this).attr('lng');
			var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
      
      //var bounds = DMap.map.getBounds();
      //log(DMap.bounds);
      
			// extend the bounds to include the new point
			DMap.bounds.extend(point);

			var marker = new google.maps.Marker({
				position: point,
				map: DMap.map,
				icon:DMap.marker_main,
				title:name
			});
			
			var html='<p><strong>'+name+'</strong><br />'+address+'</p>';
			html+='<p>Tel: '+tel+'<br>Fax: '+fax;
			google.maps.event.addListener(marker, 'click', function() {										
				if (infowindow) infowindow.close();
				infowindow = new google.maps.InfoWindow({
					content: html,
					maxWidth: 200											
				});
				infowindow.open(DMap.map, marker);
			});
			DMap.map.fitBounds(DMap.bounds);
		});
	});
};         

DMap.placeMarkerfromLink = function(el){
  
  var lat = el.attr('data-lat'),
	    lng = el.attr('data-lng'),
	    $parent = el.closest('.addressGoLeft, .addressGoRight'),
	    html = '<p><strong>'+$parent.find('a').text()+'</strong></p><p>' + $parent.find('p').text()+'</p>',
	    point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
        
	// extend the bounds to include the new point
	//DMap.bounds.extend(point);
  //console.log(marker);
	var marker = new google.maps.Marker({
		position: point,
		map: DMap.map,
		icon:DMap.marker_main,
		title:"name"
	});
	
	markersArray.push(marker);  
	
	// Clear All the markers
	DMap.clearmakers();
	
	// Set the Marker
	marker.setMap(DMap.map);  	
	
	infowindow = new google.maps.InfoWindow({
		content: html,
		maxWidth: 200											
	});
		
	// Open InfoWindow		
	DMap.map.setCenter(point); 
  DMap.map.setZoom(15);
  
  if (infowindow) infowindow.close();	
  infowindow.open(DMap.map, marker);		
	
	// Add click handler to the map
		
	google.maps.event.addListener(marker, 'click', function() {										
		if (infowindow) infowindow.close();
		infowindow.open(DMap.map, marker);
	});
	
  
};

DMap.clearmakers = function(){
  if(markersArray) {
    var _tcount = markersArray.length, i=0;
    for(i;i< _tcount;i++) {
      markersArray[i].setMap(null);
    }
  }
};

Denizen.setProductHeight=function(){
  var _productheight= jQuery('#MainProductImage').height(),
      $productcontainer = jQuery('.productCategory');
  
  //if(_productheight>700)
  
    $productcontainer.animate({
      minHeight:_productheight<700? 700:_productheight
    },1000);
      
};

// Delete Comment

function deletecomment(el, commentid, commentnid){
$.ajax({
  url: "/delete-comment-processor?cid="+commentid+"&cnid="+commentnid,
  context: document.body,
  success: function(){
  $el = $(el);
  
  $el.closest('li').fadeOut();
  }
  });
  // Send an Ajax Request Here : XZ
  
  /*
  $.post('url',function(data){
    
  })
  */
}


// delete tag
function deletetag(el, nodeid, termid){
$.ajax({
  url: "/term-removal-processor?nid="+nodeid+"&tid="+termid,
  context: document.body,
  success: function(){
  $el = $(el);
  
  $el.closest('li').fadeOut();
  }
  });
  // Send an Ajax Request Here : XZ
  
  /*
  $.post('url',function(data){
    
  })
  */
}	

// delete photo
function deletephoto(el, photoid, nodeid){
$.ajax({
  url: "/photo-removal-processor?nid="+nodeid+"&phid="+photoid,
  context: document.body,
  success: function(){
  $el = $(el);
  
  // $el.closest('li').fadeOut();
  }
  });
  // Send an Ajax Request Here : XZ
  
  /*
  $.post('url',function(data){
    
  })
  */
}	

// End Google Map Locator 

$(window).load(function(){
  
  // Init
  Denizen.init();
  
  // Initialize SlideShow
  
  if($('.slideShowWrapper').length) $('.slideShowWrapper').slideshow();
  
  // Initialize Slider
  
  if($('.sliderThumbs').length) $('.sliderThumbs').slideshow({
    autoplay:false,
    pagerthumbs:true,
    ajax:true
  });
  
  // Product Thumbs
  
  if($('.productThumbs').length) $('.productThumbs').slideshow({
    autoplay:false,
    pagerthumbs:true,
    pagerid:'#ProductThumbs',
    paginate:false
  });
  
  // Promotions Slideshow
  
  if($('.promotionWrapper').length) $('.promotionWrapper').slideshow({
    autoplay:false
  });
  
  // Paginate Carousel
  var $carousel = $('.carousel');
  $carousel.find('ul').paginate({
    perpage:7,
    itemwidth:103
  },function(){
    var _activehref =  $carousel.find('li.active > a').attr("href")||$carousel.find('li:first > a').attr("href");
    $('#ProductDetail').load(_activehref, function(){
      Denizen.setProductHeight();
    });
  });
  

  // Add Click handler to carousel
    
  var $item = $carousel.find('li').click(function(e){
      $item = $(this);
      url = $item.find('a').attr("href");
      $item.siblings().removeClass("active");
      $(this).addClass("active");
      $('#ProductDetail').empty().html(Denizen.loader).load(url, Denizen.setProductHeight);
      $('html,body').animate({
        scrollTop:0
      },1000);
       e.preventDefault();
    });
  
  
  // Colorbox in product category page - Removed March 3
  /*
  if($('.productCategory').length){
	
		$.colorbox({
			html:'<div class="denizenColorbox"><h2>you are classic skinny</h2><p><a href="#" class="linkExplore">Explore</a></p></div>',
			opacity:0.5,
			width:620
		});
	}*/
	
	// Initialize Colorbox 
	
	$('.colorbox').live('click', function() {
    $.fn.colorbox({href:$(this).attr('href'), open:true});
    return false;
  });
  
	
	// Bind Product Thumbnail Click
	
	$('.productthumbs a').live('click',function(e){
	  e.preventDefault();
	  $('#MainProductImage').hide().attr("src",this.href).one('load',function(){
	    $(this).fadeIn();
	    Denizen.setProductHeight();
	  });
	});
	
	
	// Bind Close Button
	
	$('.linkExplore').live('click',function(e){
		e.preventDefault();
		$.colorbox.close();
	});
  
  // Vertical Align
  
  $('.panel .meta').each(function(){
    $(this).vAlign();
  });
  
  // AutoComplete Search
  
  //$( "#Search" ).autocomplete({
		//source: searchdata
	//});
	
	// Open Login
	
	var $droppanels = $('.signIn, .memberPanel');
	
	$droppanels.each(function(){
	  var $this = $(this);
	  $this.find('a').eq(0).click(function(e){
  	  e.preventDefault();	  
  	  $(this)
  	    .parent()
  	    .siblings()
  	    .removeClass("active")
  	    .end()
  	    .addClass("active");	  
	    
	    $('body').bind('click',function(){
	      $droppanels.removeClass("active");
	    });	  
	    
	    $droppanels.click(function(e){ e.stopPropagation();})
	  });
	});
	
	// Favorite Page
	
	$('.favorite').find('.panel:nth-child(4n+4)').css("margin-right",0);
	
	//Startup Page
	
	var $dbutton = $('#Thumbs').find('.deleteStartup')
	             .click(function(e){
	               var $this = $(this);	               
	               $this.closest('li').fadeOut();
	               
	               // Send an Ajax Request Here : XZ
	               
	               /*
                 $.post('url',function(data){

                 })
                 */
                 
	  e.preventDefault();
	})
	
	
	// Checkbox replacement
	
	$('body.create, body.editprofile').find('input:checkbox').checkbox(); 
	
	$('select').uniform();
	
	// Delete My Startups
	//moved to actual page

	
	
	$('#submitBigBet').denizenmodal({
    	  title:'Alert',
    	  showok:true,
    	  content:function(){
var errors =[];
    	    $('#CreateBigBetForm').find('[data-required]').each(function(){
    	      var $thisField = $(this);
              
            if($thisField[0].type == 'checkbox'){
              if($thisField[0].checked!=true){
                errors.push($thisField.attr('data-required-error'));
              }
            }
            else if($thisField.attr('class') == "PhotosUpload") {
              if ($("#share1 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share1 .row .PhotosUpload").attr('data-required-error'));
              }
            }              
            else{
              if($thisField.val()==''){
                errors.push($thisField.attr('data-required-error'));
              }            
            }

    	    });


          if ($('#share2').is(':visible')) {
            if ($("#share2 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share2 .row .Writeup").val() != "") {
              if ($("#share2 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share2 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share2 .row .Writeup").val() == "") {
                errors.push($("#share2 .row .Writeup").attr('data-missing-error'));
              }
            }
          }

          if ($('#share3').is(':visible')) {
            if ($("#share3 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share3 .row .Writeup").val() != "") {          
              if ($("#share3 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share3 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share3 .row .Writeup").val() == "") {
                errors.push($("#share3 .row .Writeup").attr('data-missing-error'));
              }   
            }
          }   
          if ($('#share4').is(':visible')) {
            if ($("#share4 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share4 .row .Writeup").val() != "") {          
              if ($("#share4 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share4 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share4 .row .Writeup").val() == "") {
                errors.push($("#share4 .row .Writeup").attr('data-missing-error'));
              }
            }
          }                 
          if ($('#share5').is(':visible')) {
            if ($("#share5 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share5 .row .Writeup").val() != "") {          
              if ($("#share5 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share5 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share5 .row .Writeup").val() == "") {
                errors.push($("#share5 .row .Writeup").attr('data-missing-error'));
              }
            }          
          }          
          if ($('#share6').is(':visible')) {
            if ($("#share6 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share6 .row .Writeup").val() != "") {          
              if ($("#share6 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share6 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share6 .row .Writeup").val() == "") {
                errors.push($("#share6 .row .Writeup").attr('data-missing-error'));
              }
            }              
          }          
          if ($('#share7').is(':visible')) {
            if ($("#share7 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share7 .row .Writeup").val() != "") {          
              if ($("#share7 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share7 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share7 .row .Writeup").val() == "") {
                errors.push($("#share7 .row .Writeup").attr('data-missing-error'));
              }
            }              
          }          
          if ($('#share8').is(':visible')) {  
            if ($("#share8 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share8 .row .Writeup").val() != "") {          
              if ($("#share8 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share8 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share8 .row .Writeup").val() == "") {
                errors.push($("#share8 .row .Writeup").attr('data-missing-error'));
              }
            }              
          }          
          if ($('#share9').is(':visible')) {
            if ($("#share9 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share9 .row .Writeup").val() != "") {          
              if ($("#share9 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share9 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share9 .row .Writeup").val() == "") {
                errors.push($("#share9 .row .Writeup").attr('data-missing-error'));
              }
            }              
          }          
          if ($('#share10').is(':visible')) {
            if ($("#share10 .row .PhotosUpload ul li:first").html().trim() != "" || $("#share10 .row .Writeup").val() != "") {          
              if ($("#share10 .row .PhotosUpload ul li:first").html().trim() == "") {
                errors.push($("#share10 .row .PhotosUpload").attr('data-missing-error'));
              }
              if ($("#share10 .row .Writeup").val() == "") {
                errors.push($("#share10 .row .Writeup").attr('data-missing-error'));
              }
            }              
          }          

    	    return errors.join('<br>');
         }
});
	
	// Invoke Denizen Modal  - Create Profile Form
	
	var $forms = $('#CreateStartupForm, #ContactForm, #EditProfileForm, #searchStoreForm');

	$forms.each(function(){
    $('input:file').uniform();
  
	  var $form = $(this);
	  
	  if($form.length){
	    $form.denizenmodal({
    	  title:"Alert",
    	  showok:true,
    	  content:function(){

    	    // Do all the validation Here And output the error. If no error, return nothing =>Modal box wont be shown. 
    	    var errors =[];
    	    $form.find('[data-required]').each(function(){
    	      var $this = $(this);

              
            if($this[0].type == 'checkbox'){
              if($this[0].checked!=true){
                errors.push($this.attr("data-required-error"));
              }
            }else{
              if($this.val()==''){
                errors.push($this.attr("data-required-error"));
              }            
            }

    	    });
          
          if($form.attr('id')=='ContactForm'){
            if ($("input[name=email]").val() != "") {
            var email = $("input[name=email]").val();
            var emailRegExp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/;
            if (!emailRegExp.test(email)) {
              errors.push($("input[name=email]").attr("data-required-error"));
            }            
            }
          }
          
          //specially for Create Startups
          if($form.attr('id')=='CreateStartupForm'){
            if($("input[name=Interest[]]:checked").length < 1){
              errors.push($("ul.interests").attr("data-required-error"));
            }
            var valid_url = new RegExp('http://((www|v)\.)?(tudou|youtube|youku).com/[a-zA-Z0-9_-]*', ''); 
            
            var bothempty = 0;
            
           if($("input[name=VideoURL]").val() == "") {
            bothempty++;
           }
           if ($("#PhotosUpload ul li:first").html() != null) {
            if ($("#PhotosUpload ul li:first").html().trim() == "") {
              bothempty++;
            }
           }
           else {
             bothempty++;
           }
          if (bothempty == 2) {
               errors.push($("input[name=VideoURL]").attr("data-required-error"));
               }
           else if($("input[name=VideoURL]").val() != "" && !valid_url.test($("input[name=VideoURL]").val())){ 
               errors.push($("input[name=VideoURL]").attr("data-validation-error"));
            }

          if($("#Agree:checked").val()!="on" || $("#Agree1:checked").val()!="on" || $("#Agree2:checked").val()!="on" || $("#Agree3:checked").val()!="on"){
                errors.push($("#Agree1").attr("data-validation-error"));
              }  
          }

    	    return errors.join('<br>');

    	  }
    	});
	  }
	  
	});
	 
  
  // Invoke Denizen Modal Globally for all link with rel="denizenmodal"
  
  $('[rel*=denizenmodal]').denizenmodal({
      bordercolor:'#0b91ce',
      onload:function(){
        $('#DenizenModal input:checkbox').checkbox();
      }
      
  });
  
  
  // Inplace Editable
  
  $('#editButton').click(function(e){
    e.preventDefault();
    $('#editButton').toggle(500);
    var $edit = $(this),
        $next = $edit.next(),
        _id = $edit.attr("data-id"),
        _nid = $edit.attr("data-nid"),
        $textarea = '<form action="/inline-node-save-processor" method="post" id="SaveEditForm"><input type="hidden" name="nid" id="nid" value="'+_nid+'"><input type="hidden" name="ntype" value="start_up"><p><textarea name="nodeBody" id="nodeBody" row="10" cols="2">'+$next.text()+'</textarea><button type="submit" class="submit" id="SaveEdit">Save</button></p></form>';
    
    $next.replaceWith($textarea);
    
    // Bind Submit
    
    $('#SaveEditForm').submit(function(e){
      e.preventDefault();
      var $form = $(this);
      //console.log(dataList);
      $.post('/inline-node-save-processor', $form.serialize(), function(data){
        newBodyText = $('#nodeBody').val();
        $form.replaceWith('<p>'+newBodyText+'</p>');
        $('#editButton').toggle(500);
      });
      
    });
    //log($text);
    
  });
  
  

  
});

