code
stringlengths
1
2.08M
language
stringclasses
1 value
$(function() { $(".dial").knob(); // knob //jQuery UI Sliders //------------------------ $('#demoskylo').on('click',function(){ $(document).skylo('start'); setTimeout(function(){ $(document).skylo('set',50); },1000); setTimeout(function(){ $(document).skylo('end'); },1500); }); $('#setskylo').on('click',function(){ $(document).skylo('show',function(){ $(document).skylo('set',50); }); }); $('#getskylo').on('click',function(){ alert($(document).skylo('get')+'%'); }); $('#inchskylo').on('click',function(){ $(document).skylo('show',function(){ $(document).skylo('inch',10); }); }); //jQuery UI Sliders //------------------------ $(".slider-basic").slider(); // basic sliders // snap inc $("#slider-snap-inc").slider({ value: 100, min: 0, max: 1000, step: 100, slide: function (event, ui) { $("#slider-snap-inc-amount").text("$" + ui.value); } }); $("#slider-snap-inc-amount").text("$" + $("#slider-snap-inc").slider("value")); // range slider $("#slider-range").slider({ range: true, min: 0, max: 500, values: [75, 300], slide: function (event, ui) { $("#slider-range-amount").text("$" + ui.values[0] + " - $" + ui.values[1]); } }); $("#slider-range-amount").text("$" + $("#slider-range").slider("values", 0) + " - $" + $("#slider-range").slider("values", 1)); //range max $("#slider-range-max").slider({ range: "max", min: 1, max: 10, value: 2, slide: function (event, ui) { $("#slider-range-max-amount").text(ui.value); } }); $("#slider-range-max-amount").text($("#slider-range-max").slider("value")); // range min $("#slider-range-min").slider({ range: "min", value: 37, min: 1, max: 700, slide: function (event, ui) { $("#slider-range-min-amount").text("$" + ui.value); } }); $("#slider-range-min-amount").text("$" + $("#slider-range-min").slider("value")); // setup graphic EQ $("#slider-eq > span").each(function () { // read initial values from markup and remove that var value = parseInt($(this).text(), 10); $(this).empty().slider({ range: "min", min: 0, max: 100, value: value, orientation: "vertical" }); }); // vertical slider $("#slider-vertical").slider({ orientation: "vertical", range: "min", min: 0, max: 100, value: 60, slide: function (event, ui) { $("#slider-vertical-amount").text(ui.value); } }); $("#slider-vertical-amount").text($("#slider-vertical").slider("value")); // vertical range sliders $("#slider-range-vertical").slider({ orientation: "vertical", range: true, values: [17, 67], slide: function (event, ui) { $("#slider-range-vertical-amount").text("$" + ui.values[0] + " - $" + ui.values[1]); } }); $("#slider-range-vertical-amount").text("$" + $("#slider-range-vertical").slider("values", 0) + " - $" + $("#slider-range-vertical").slider("values", 1)); //Easy Pie Chart //------------------------ try { //Easy Pie Chart $('.easypiechart#newvisits').easyPieChart({ barColor: "#16a085", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#bouncerate').easyPieChart({ barColor: "#7ccc2e", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#clickrate').easyPieChart({ barColor: "#e84747", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#covertionrate').easyPieChart({ barColor: "#8e44ad", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('#updatePieCharts').on('click', function() { $('.easypiechart#newvisits').data('easyPieChart').update(Math.random()*100); $('.easypiechart#bouncerate').data('easyPieChart').update(Math.random()*100); $('.easypiechart#clickrate').data('easyPieChart').update(Math.random()*100); $('.easypiechart#covertionrate').data('easyPieChart').update(Math.random()*100); return false; }); } catch(error) {} });
JavaScript
$(function(){ // activate Nestable for list 1 $('#nestable_list_1').nestable({ group: 1 }) .on('change', updateOutput); // activate Nestable for list 2 $('#nestable_list_2').nestable({ group: 1 }) .on('change', updateOutput); // output initial serialised data updateOutput($('#nestable_list_1').data('output', $('#nestable_list_1_output'))); updateOutput($('#nestable_list_2').data('output', $('#nestable_list_2_output'))); $('#nestable_list_menu').on('click', function (e) { var target = $(e.target), action = target.data('action'); if (action === 'expand-all') { $('.dd').nestable('expandAll'); } if (action === 'collapse-all') { $('.dd').nestable('collapseAll'); } }); $('#nestable_list_3').nestable(); function updateOutput(e) { var list = e.length ? e : $(e.target), output = list.data('output'); if (window.JSON) { output.val(window.JSON.stringify(list.nestable('serialize'))); //, null, 2)); } else { output.val('JSON browser support required for this demo.'); } } });
JavaScript
$(function(){ var lineChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("line-chart").getContext("2d")).Line(lineChartData); var barChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("bar-chart").getContext("2d")).Bar(barChartData); var radarChartData = { labels : ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] } var myRadar = new Chart(document.getElementById("radar-chart").getContext("2d")).Radar(radarChartData,{scaleShowLabels : false, pointLabelFontSize : 10}); var pieData = [ { value: 30, color:"#F38630" }, { value : 50, color : "#E0E4CC" }, { value : 100, color : "#69D2E7" } ]; var myPie = new Chart(document.getElementById("pie-chart").getContext("2d")).Pie(pieData); var chartData = [ { value : Math.random(), color: "#D97041" }, { value : Math.random(), color: "#C7604C" }, { value : Math.random(), color: "#21323D" }, { value : Math.random(), color: "#9D9B7F" }, { value : Math.random(), color: "#7D4F6D" }, { value : Math.random(), color: "#584A5E" } ]; var myPolarArea = new Chart(document.getElementById("polar-area-chart").getContext("2d")).PolarArea(chartData); var doughnutData = [ { value: 30, color:"#F7464A" }, { value : 50, color : "#46BFBD" }, { value : 100, color : "#FDB45C" }, { value : 40, color : "#949FB1" }, { value : 120, color : "#4D5360" } ]; var myDoughnut = new Chart(document.getElementById("donut-chart").getContext("2d")).Doughnut(doughnutData); });
JavaScript
$(function(){ //Uncomment the line and switch modes //$.fn.editable.defaults.mode = 'inline'; //editables $('#username').editable({ type: 'text', pk: 1, name: 'username', title: 'Enter username' }); $('#firstname').editable({ validate: function(value) { if($.trim(value) == '') return 'This field is required'; } }); $('#sex').editable({ prepend: "not selected", source: [ {value: 1, text: 'Male'}, {value: 2, text: 'Female'} ], display: function(value, sourceData) { var colors = {"": "gray", 1: "green", 2: "blue"}, elem = $.grep(sourceData, function(o){return o.value == value;}); if(elem.length) { $(this).text(elem[0].text).css("color", colors[value]); } else { $(this).empty(); } } }); $('#status').editable(); $('#group').editable({ showbuttons: false }); $('#dob').editable(); $('#comments').editable({ showbuttons: 'bottom' }); //inline $('#inline-username').editable({ type: 'text', pk: 1, name: 'username', title: 'Enter username', mode: 'inline' }); $('#inline-firstname').editable({ validate: function(value) { if($.trim(value) == '') return 'This field is required'; }, mode: 'inline' }); $('#inline-sex').editable({ prepend: "not selected", mode: 'inline', source: [ {value: 1, text: 'Male'}, {value: 2, text: 'Female'} ], display: function(value, sourceData) { var colors = {"": "gray", 1: "green", 2: "blue"}, elem = $.grep(sourceData, function(o){return o.value == value;}); if(elem.length) { $(this).text(elem[0].text).css("color", colors[value]); } else { $(this).empty(); } } }); $('#inline-status').editable({mode: 'inline'}); $('#inline-group').editable({ showbuttons: false, mode: 'inline' }); $('#inline-dob').editable({mode: 'inline'}); $('#inline-comments').editable({ showbuttons: 'bottom', mode: 'inline' }); });
JavaScript
// ------------------------------- // Initialize Data Tables // ------------------------------- $(document).ready(function() { $('.datatables').dataTable({ "sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page", "sSearch": "" } }); $('.dataTables_filter input').addClass('form-control').attr('placeholder','Search...'); $('.dataTables_length select').addClass('form-control'); });
JavaScript
// ---------------------- // Inline table editor // ---------------------- $(function () { $('#editable td').editable({ closeOnEnter : true, event:"click", touch : true, callback: function(data) { if( data.fontSize ) { alert('You changed the font size to '+data.fontSize); } } }); }); // ------------------------------- // Initialize Data Tables // ------------------------------- $(document).ready(function() { $('.datatables').dataTable({ "sDom": "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page", "sSearch": "" } }); $('.dataTables_filter input').addClass('form-control').attr('placeholder','Search...'); $('.dataTables_length select').addClass('form-control');} ); //------------------------- // With Table Tools Editor //------------------------- var editor; $(function () { editor = new $.fn.dataTable.Editor({ "ajaxUrl":"assets/demo/source.json", "domTable":"#crudtable", "fields":[ { "label":"Browser:", "name":"browser" }, { "label":"Rendering engine:", "name":"engine" }, { "label":"Platform:", "name":"platform" }, { "label":"Version:", "name":"version" }, { "label":"CSS grade:", "name":"grade" } ] }); $('#crudtable').dataTable({ "sDom":"<'row'<'col-sm-6'T><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'p>>", "sAjaxSource":"assets/demo/source.json", "bServerSide": false, "bAutoWidth": false, "bDestroy": true, "aoColumns":[ { "mData":"browser" }, { "mData":"engine" }, { "mData":"platform" }, { "mData":"version", "sClass":"center" }, { "mData":"grade", "sClass":"center" } ], "oTableTools":{ "sRowSelect":"multi", "aButtons":[ { "sExtends":"editor_create", "editor":editor }, { "sExtends":"editor_edit", "editor":editor }, { "sExtends":"editor_remove", "editor":editor } ] } }); $('.dataTables_filter input').addClass('form-control').attr('placeholder','Search...'); $('.dataTables_length select').addClass('form-control'); //add icons $("#ToolTables_crudtable_0").prepend('<i class="fa fa-plus"/> '); $("#ToolTables_crudtable_1").prepend('<i class="fa fa-pencil-square-o"/> '); $("#ToolTables_crudtable_2").prepend('<i class="fa fa-times-circle"/> '); });
JavaScript
/** * Basic Map */ $(document).ready(function () { //Basic Maps var map = new GMaps({ el:'#basic-map', lat:-12.043333, lng:-77.028333 }); GMaps.geolocate({ success:function (position) { map.setCenter(position.coords.latitude, position.coords.longitude); }, error:function (error) { alert('Geolocation failed: ' + error.message); }, not_supported:function () { alert("Your browser does not support geolocation"); } }); //advance Route var route = new GMaps({ el:'#advance-route', lat:-12.043333, lng:-77.028333 }); $('#start_travel').click(function (e) { e.preventDefault(); route.travelRoute({ origin:[-12.044012922866312, -77.02470665341184], destination:[-12.090814532191756, -77.02271108990476], travelMode:'driving', step:function (e) { $('#instructions').append('<li>' + e.instructions + '</li>'); $('#instructions li:eq(' + e.step_number + ')').delay(450 * e.step_number).fadeIn(200, function () { route.setCenter(e.end_location.lat(), e.end_location.lng()); route.drawPolyline({ path:e.path, strokeColor:'#131540', strokeOpacity:0.6, strokeWeight:6 }); }); } }); }); //street view panaroma var panorama = GMaps.createPanorama({ el:'#panorama', lat:42.3455, lng:-71.0983 }); //fusion table var fusion, infoWindow; infoWindow = new google.maps.InfoWindow({}); fusion = new GMaps({ el:'#fusion', zoom:11, lat:41.850033, lng:-87.6500523 }); fusion.loadFromFusionTables({ query:{ select:'\'Geocodable address\'', from:'1mZ53Z70NsChnBMm-qEYmSDOvLXgrreLTkQUvvg' }, suppressInfoWindows:true, events:{ click:function (point) { infoWindow.setContent('You clicked here!'); infoWindow.setPosition(point.latLng); infoWindow.open(fusion.map); } } }); //polyLInes path = [[-12.044012922866312, -77.02470665341184], [-12.05449279282314, -77.03024273281858], [-12.055122327623378, -77.03039293652341], [-12.075917129727586, -77.02764635449216], [-12.07635776902266, -77.02792530422971], [-12.076819390363665, -77.02893381481931], [-12.088527520066453, -77.0241058385925], [-12.090814532191756, -77.02271108990476]]; var polylines = new GMaps({ el: '#polylines', lat: -12.043333, lng: -77.028333, click: function(e){ console.log(e); } }); polylines.drawPolyline({ path: path, strokeColor: '#131540', strokeOpacity: 0.6, strokeWeight: 6 }); //geo coding var geoCoding = new GMaps({ el: '#geocoding', lat: -12.043333, lng: -77.028333 }); $('#geocoding_form').submit(function(e){ e.preventDefault(); GMaps.geocode({ address: $('#address').val().trim(), callback: function(results, status){ if(status=='OK'){ var latlng = results[0].geometry.location; geoCoding.setCenter(latlng.lat(), latlng.lng()); geoCoding.addMarker({ lat: latlng.lat(), lng: latlng.lng() }); } } }); }); //polygons var polygons = new GMaps({ el: '#polygons', lat: -12.043333, lng: -77.028333 }); var path = [[-12.040397656836609,-77.03373871559225], [-12.040248585302038,-77.03993927003302], [-12.050047116528843,-77.02448169303511], [-12.044804866577001,-77.02154422636042]]; polygon = polygons.drawPolygon({ paths: path, strokeColor: '#BBD8E9', strokeOpacity: 1, strokeWeight: 3, fillColor: '#BBD8E9', fillOpacity: 0.6 }); });
JavaScript
// Demo for FullCalendar with Drag/Drop internal $(document).ready(function() { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var calendar = $('#calendar-drag').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, selectable: true, selectHelper: true, select: function(start, end, allDay) { var title = prompt('Event Title:'); if (title) { calendar.fullCalendar('renderEvent', { title: title, start: start, end: end, allDay: allDay }, true // make the event "stick" ); } calendar.fullCalendar('unselect'); }, editable: true, events: [ { title: 'All Day Event', start: new Date(y, m, 8), backgroundColor: '#efa131' }, { title: 'Long Event', start: new Date(y, m, d-5), end: new Date(y, m, d-2), backgroundColor: '#85c744' }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d-3, 16, 0), allDay: false, backgroundColor: '#e74c3c' }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d+4, 16, 0), allDay: false, backgroundColor: '#e74c3c' }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false, backgroundColor: '#76c4ed' }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false, backgroundColor: '#34495e' }, { title: 'Birthday Party', start: new Date(y, m, d+1, 19, 0), end: new Date(y, m, d+1, 22, 30), allDay: false, backgroundColor: '#2bbce0' }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/', backgroundColor: '#f1c40f' } ], buttonText: { prev: '<i class="fa fa-angle-left"></i>', next: '<i class="fa fa-angle-right"></i>', prevYear: '<i class="fa fa-angle-double-left"></i>', // << nextYear: '<i class="fa fa-angle-double-right"></i>', // >> today: 'Today', month: 'Month', week: 'Week', day: 'Day' } }); }); // Demo for FullCalendar with Drag/Drop external $(document).ready(function() { /* initialize the external events -----------------------------------------------------------------*/ $('#external-events div.external-event').each(function() { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end var eventObject = { title: $.trim($(this).text()) // use the element's text as the event title }; // store the Event Object in the DOM element so we can get to it later $(this).data('eventObject', eventObject); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); /* initialize the calendar -----------------------------------------------------------------*/ $('#calendar-external').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, droppable: true, // this allows things to be dropped onto the calendar !!! drop: function(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); // we need to copy it, so that multiple events don't have a reference to the same object var copiedEventObject = $.extend({}, originalEventObject); // assign it the date that was reported copiedEventObject.start = date; copiedEventObject.allDay = allDay; // render the event on the calendar // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/) $('#calendar-external').fullCalendar('renderEvent', copiedEventObject, true); // is the "remove after drop" checkbox checked? if ($('#drop-remove').is(':checked')) { // if so, remove the element from the "Draggable Events" list $(this).remove(); } }, buttonText: { prev: '<i class="fa fa-angle-left"></i>', next: '<i class="fa fa-angle-right"></i>', prevYear: '<i class="fa fa-angle-double-left"></i>', // << nextYear: '<i class="fa fa-angle-double-right"></i>', // >> today: 'Today', month: 'Month', week: 'Week', day: 'Day' } }); });
JavaScript
/* Initialize Image Filter and Sort Plugin for Gallery */ $(function(){ $('.gallery').mixitup({ onMixEnd: function() { onclickofimg(); } }); }); /* Bind filter with selectbox */ $("#galleryfilter").change(function(e) { var cat = $("#galleryfilter option:selected").data('filter'); $('.gallery').mixitup('filter', cat); }); /* Switch between grid and list view */ $('#GoList').click(function(e) { $('.gallery').mixitup('toList'); $(this).addClass('active'); var delay = setTimeout(function(){ $('.gallery').addClass('full-width'); $('#GoGrid').removeClass('active'); }); }); $('#GoGrid').click(function(e) { $('#GoList').removeClass('active'); $(this).addClass('active'); var delay = setTimeout(function(){ $('.gallery').mixitup('toGrid'); $('.gallery').removeClass('full-width'); }); }); onclickofimg(); //On click of img function onclickofimg () { $('.mix a').click(function(e){ e.preventDefault(); $('.modal-title').empty(); $('.modal-body').empty(); var title = $(this).siblings('h4').html(); $('.modal-title').html(title); var img= '<img class="img-responsive" src=' +$(this).attr("href")+ '></img>'; $(img).appendTo('.modal-body'); $('#gallarymodal').modal({show:true}); }); }
JavaScript
jQuery(document).ready(function() { $(".demodrop").pulsate({ color: "#2bbce0", repeat: 10 }); $("#threads,#comments,#users").niceScroll({horizrailenabled:false,railoffset: {left:0}}); try { //Easy Pie Chart $('.easypiechart#returningvisits').easyPieChart({ barColor: "#85c744", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#newvisitor').easyPieChart({ barColor: "#f39c12", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#clickrate').easyPieChart({ barColor: "#e73c3c", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'square', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('#updatePieCharts').on('click', function() { $('.easypiechart#returningvisits').data('easyPieChart').update(Math.random()*100); $('.easypiechart#newvisitor').data('easyPieChart').update(Math.random()*100); $('.easypiechart#clickrate').data('easyPieChart').update(Math.random()*100); return false; }); } catch(e) {} //Date Range Picker $('#daterangepicker2').daterangepicker( { ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)], 'Last 7 Days': [moment().subtract('days', 6), moment()], 'Last 30 Days': [moment().subtract('days', 29), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')] }, opens: 'left', startDate: moment().subtract('days', 29), endDate: moment() }, function(start, end) { $('#daterangepicker2 span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } ); //Sparklines $("#indexinfocomments").sparkline([12 + randValue(),8 + randValue(),10 + randValue(), 21 + randValue(), 16 + randValue(), 9 + randValue(), 15 + randValue(), 8 + randValue() ,10 + randValue(),19 + randValue()], { type: 'bar', barColor: '#f1948a', height: '45', barWidth: 7}); $("#indexinfolikes").sparkline([120 + randValue(),87 + randValue(),108 + randValue(), 121 + randValue(), 85 + randValue(), 95 + randValue(), 185 + randValue(), 125 + randValue() ,154 + randValue(),109 + randValue()], { type: 'bar', barColor: '#f5c783', height: '45', barWidth: 7}); $("#indexvisits").sparkline([7914 + randValue(),2795 + randValue(),3256 + randValue(), 3018 + randValue(), 2832 + randValue() ,5261 + randValue(),6573 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#556b8d', fillColor: 'rgba(85,107,141,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#556b8d', spotRadius: 3, maxSpotColor: false}); $("#indexpageviews").sparkline([8263 + randValue(),6314 + randValue(),10467 + randValue(), 12123 + randValue(), 11125 + randValue() ,13414 + randValue(),15519 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#4f8edc', fillColor: 'rgba(79,142,220,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#4f8edc', spotRadius: 3, maxSpotColor: false}); $("#indexpagesvisit").sparkline([7.41 + randValue(),6.12 + randValue(),6.8 + randValue(), 5.21 + randValue(), 6.15 + randValue() ,7.14 + randValue(),6.19 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#a6b0c2', fillColor: 'rgba(166,176,194,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#a6b0c2', spotRadius: 3, maxSpotColor: false}); $("#indexavgvisit").sparkline([5.31 + randValue(),2.18 + randValue(),1.06 + randValue(), 3.42 + randValue(), 2.51 + randValue() ,1.45 + randValue(),4.01 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#85c744', fillColor: 'rgba(133,199,68,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#85c744', spotRadius: 3, maxSpotColor: false}); $("#indexnewvisits").sparkline([70.14 + randValue(),72.95 + randValue(),77.56 + randValue(), 78.18 + randValue(), 76.32 + randValue() ,73.61 + randValue(),74.73 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#efa131', fillColor: 'rgba(239,161,49,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#efa131', spotRadius: 3, maxSpotColor: false}); $("#indexbouncerate").sparkline([29.14 + randValue(),27.95 + randValue(),32.56 + randValue(), 30.18 + randValue(), 28.32 + randValue() ,32.61 + randValue(),35.73 + randValue()], { lineWidth: 1.5, type: 'line', width: '90px', height: '45px', lineColor: '#e74c3c', fillColor: 'rgba(231,76,60,0.1)', spotColor: false, minSpotColor: false, highlightLineColor: '#d2d3d6', highlightSpotColor: '#e74c3c', spotRadius: 3, maxSpotColor: false}); //Flot function randValue() { return (Math.floor(Math.random() * (2))); } var viewcount = [ [1, 787 + randValue()], [2, 740 + randValue()], [3, 560 + randValue()], [4, 860 + randValue()], [5, 750 + randValue()], [6, 910 + randValue()], [7, 730 + randValue()] ]; var uniqueviews = [ [1, 179 + randValue()], [2, 320 + randValue()], [3, 120 + randValue()], [4, 400 + randValue()], [5, 573 + randValue()], [6, 255 + randValue()], [7, 366 + randValue()] ]; var usercount = [ [1, 70 + randValue()], [2, 260 + randValue()], [3, 30 + randValue()], [4, 147 + randValue()], [5, 333 + randValue()], [6, 155 + randValue()], [7, 166 + randValue()] ]; var plot_statistics = $.plot($("#site-statistics"), [{ data: viewcount, label: "View Count" }, { data: uniqueviews, label: "Unique Views" }, { data: usercount, label: "User Count" }], { series: { lines: { show: true, lineWidth: 1.5, fill: 0.05 }, points: { show: true }, shadowSize: 0 }, grid: { labelMargin: 10, hoverable: true, clickable: true, borderWidth: 0 }, colors: ["#a6b0c2", "#71a5e7", "#aa73c2"], xaxis: { tickColor: "transparent", ticks: [[1, "S"], [2, "M"], [3, "T"], [4, "W"], [5, "T"], [6, "F"], [7, "S"]], tickDecimals: 0, autoscaleMargin: 0, font: { color: '#8c8c8c', size: 12 } }, yaxis: { ticks: 4, tickDecimals: 0, tickColor: "#e3e4e6", font: { color: '#8c8c8c', size: 12 }, tickFormatter: function (val, axis) { if (val>999) {return (val/1000) + "K";} else {return val;} } }, legend : { labelBoxBorderColor: 'transparent' } }); var d1 = [ [1, 29 + randValue()], [2, 62 + randValue()], [3, 52 + randValue()], [4, 41 + randValue()] ]; var d2 = [ [1, 36 + randValue()], [2, 79 + randValue()], [3, 66 + randValue()], [4, 24 + randValue()] ]; for (var i = 1; i < 5; i++) { d1.push([i, parseInt(Math.random() * 1)]); d2.push([i, parseInt(Math.random() * 1)]); } var ds = new Array(); ds.push({ data:d1, label: "Budget", bars: { show: true, barWidth: 0.2, order: 1 } }); ds.push({ data:d2, label: "Actual", bars: { show: true, barWidth: 0.2, order: 2, } }); var variance = $.plot($("#budget-variance"), ds, { series: { bars: { show: true, fill: 0.75, lineWidth: 0 } }, grid: { labelMargin: 10, hoverable: true, clickable: true, tickColor: "#e6e7e8", borderWidth: 0 }, colors: ["#8D96AF", "#556b8d"], xaxis: { autoscaleMargin: 0.05, tickColor: "transparent", ticks: [[1, "Q1"], [2, "Q2"], [3, "Q3"], [4, "Q4"]], tickDecimals: 0, font: { color: '#8c8c8c', size: 12 } }, yaxis: { ticks: [0, 25, 50, 75, 100], font: { color: '#8c8c8c', size: 12 }, tickFormatter: function (val, axis) { return "$" + val + "K"; } }, legend : { labelBoxBorderColor: 'transparent' } }); var previousPoint = null; $("#site-statistics").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY-7, item.series.label + ": " + Math.round(y)); } } else { $("#tooltip").remove(); previousPoint = null; } }); var previousPointBar = null; $("#budget-variance").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPointBar != item.dataIndex) { previousPointBar = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX+20, item.pageY, item.series.label + ": $" + Math.round(y)+"K"); } } else { $("#tooltip").remove(); previousPointBar = null; } }); function showTooltip(x, y, contents) { $('<div id="tooltip" class="tooltip top in"><div class="tooltip-inner">' + contents + '<\/div><\/div>').css({ display: 'none', top: y - 40, left: x - 55, }).appendTo("body").fadeIn(200); } var container = $("#server-load"); // Determine how many data points to keep based on the placeholder's initial size; // this gives us a nice high-res plot while avoiding more than one point per pixel. var maximum = container.outerWidth() / 2 || 300; var data = []; function getRandomData() { if (data.length) { data = data.slice(1); } while (data.length < maximum) { var previous = data.length ? data[data.length - 1] : 50; var y = previous + Math.random() * 10 - 5; data.push(y < 0 ? 0 : y > 100 ? 100 : y); } // zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res; } // series = [{ data: getRandomData() }]; // var plot = $.plot(container, series, { series: { lines: { show: true, lineWidth: 1.5, fill: 0.15 }, shadowSize: 0 }, grid: { labelMargin: 10, tickColor: "#e6e7e8", borderWidth: 0 }, colors: ["#f1c40f"], xaxis: { tickFormatter: function() { return ""; }, tickColor: "transparent" }, yaxis: { ticks: 2, min: 0, max: 100, tickFormatter: function (val, axis) { return val + "%"; }, font: { color: '#8c8c8c', size: 12 } }, legend: { show: true } }); // Update the random dataset at 25FPS for a smoothly-animating chart setInterval(function updateRandom() { series[0].data = getRandomData(); plot.setData(series); plot.draw(); }, 40); }); // Calendar // If screensize > 1200, render with m/w/d view, if not by default render with just title renderCalendar({left: 'title',right: 'prev,next'}); enquire.register("screen and (min-width: 1200px)", { match : function() { $('#calendar-drag').removeData('fullCalendar').empty(); renderCalendar({left: 'prev,next',center: 'title',right: 'month,basicWeek,basicDay'}); }, unmatch : function() { $('#calendar-drag').removeData('fullCalendar').empty(); renderCalendar({left: 'title',right: 'prev,next'}); } }); function renderCalendar(headertype) { // Demo for FullCalendar with Drag/Drop internal var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var calendar = $('#calendar-drag').fullCalendar({ header: headertype, selectable: true, selectHelper: true, select: function(start, end, allDay) { var title = prompt('Event Title:'); if (title) { calendar.fullCalendar('renderEvent', { title: title, start: start, end: end, allDay: allDay }, true // make the event "stick" ); } calendar.fullCalendar('unselect'); }, editable: true, events: [ { title: 'All Day Event', start: new Date(y, m, 8), backgroundColor: '#efa131' }, { title: 'Long Event', start: new Date(y, m, d-5), end: new Date(y, m, d-2), backgroundColor: '#7a869c' }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d-3, 16, 0), allDay: false, backgroundColor: '#e74c3c' }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d+4, 16, 0), allDay: false, backgroundColor: '#e74c3c' }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false, backgroundColor: '#76c4ed' }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false, backgroundColor: '#34495e' }, { title: 'Birthday Party', start: new Date(y, m, d+1, 19, 0), end: new Date(y, m, d+1, 22, 30), allDay: false, backgroundColor: '#2bbce0' }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/', backgroundColor: '#f1c40f' } ], buttonText: { prev: '<i class="fa fa-angle-left"></i>', next: '<i class="fa fa-angle-right"></i>', prevYear: '<i class="fa fa-angle-double-left"></i>', // << nextYear: '<i class="fa fa-angle-double-right"></i>', // >> today: 'Today', month: 'Month', week: 'Week', day: 'Day' } }); // Listen for click on toggle checkbox $('#select-all').click(function(event) { if(this.checked) { $('.selects :checkbox').each(function() { this.checked = true; }); } else { $('.selects :checkbox').each(function() { this.checked = false; }); } }); $( ".panel-tasks" ).sortable({placeholder: 'item-placeholder'}); $('.panel-tasks input[type="checkbox"]').click(function(event) { if(this.checked) { $(this).next(".task-description").addClass("done"); } else { $(this).next(".task-description").removeClass("done"); } }); }
JavaScript
// ------------------------------- // Demos: Form Components // ------------------------------- $(function() { //FSEditor $(".fullscreen").fseditor({maxHeight: 500}); // iPhone like button Toggle (uncommented because already activated in demo.js) // $('.toggle').toggles({on:true}); // Autogrow Textarea $('textarea.autosize').autosize({append: "\n"}); //Typeahead for Autocomplete $('.example-countries.typeahead').typeahead({ name: 'countries', prefetch: 'assets/demo/countries.json', limit: 10 }); //Color Picker $('.cpicker').colorpicker(); //Bootstrap Date Picker $('#datepicker,#datepicker2,#datepicker3').datepicker(); $('#datepicker-pastdisabled').datepicker({startDate: "today"}); $('#datepicker-startview1').datepicker({startView: 1}); //http://eternicode.github.io/bootstrap-datepicker/ //jQueryUI Time Picker $('#timepicker1,#timepicker3').timepicker(); $("#timepicker2").timepicker({ showPeriod: true, showLeadingZero: true }); $('#timepickerbtn2').click(function () { $('#timepicker2').timepicker("show"); }); $("#timepicker4").timepicker({ hours: { starts: 6, ends: 19 }, minutes: { interval: 15 }, rows: 3, showPeriodLabels: true, minuteText: 'Min' }); // Date Range Picker $(document).ready(function() { $('#daterangepicker1').daterangepicker(); }); $('#daterangepicker2').daterangepicker( { ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)], 'Last 7 Days': [moment().subtract('days', 6), moment()], 'Last 30 Days': [moment().subtract('days', 29), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')] }, opens: 'left', startDate: moment().subtract('days', 29), endDate: moment() }, function(start, end) { $('#daterangepicker2 span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } ); $('#daterangepicker3').daterangepicker({ timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A' }); //Tokenfield $('#tokenfield-jQUI').tokenfield({ autocomplete: { source: ['red','blue','green','yellow','violet','brown','purple','black','white'], delay: 100 }, showAutocompleteOnFocus: true }); $('#tokenfield-typeahead').tokenfield({ typeahead: { name: 'tags', local: ['red','blue','green','yellow','violet','brown','purple','black','white'], } }); $('#tokenfield-email') .on('beforeCreateToken', function (e) { var token = e.token.value.split('|') e.token.value = token[1] || token[0] e.token.label = token[1] ? token[0] + ' (' + token[1] + ')' : token[0] }) .on('afterCreateToken', function (e) { // Über-simplistic e-mail validation var re = /\S+@\S+\.\S+/ var valid = re.test(e.token.value) if (!valid) { $(e.relatedTarget).addClass('invalid') } }) .on('beforeEditToken', function (e) { if (e.token.label !== e.token.value) { var label = e.token.label.split(' (') e.token.value = label[0] + '|' + e.token.value } }) .on('removeToken', function (e) { alert('Token removed! Token value was: ' + e.token.value) }) .on('preventDuplicateToken', function (e) { alert('Duplicate detected! Token value is: ' + e.token.value) }) .tokenfield(); //SELECT2 //For detailed documentation, see: http://ivaynberg.github.io/select2/index.html //Populate all select boxes with from select#source var opts=$("#source").html(), opts2="<option></option>"+opts; $("select.populate").each(function() { var e=$(this); e.html(e.hasClass("placeholder")?opts2:opts); }); //select2 $("#e1,#e2").select2({width: 'resolve'}); $("#e3").select2({ minimumInputLength: 2, width: 'resolve' }); $("#e5").select2({ minimumInputLength: 1, width: 'resolve', query: function (query) { var data = {results: []}, i, j, s; for (i = 1; i < 5; i++) { s = ""; for (j = 0; j < i; j++) {s = s + query.term;} data.results.push({id: query.term + i, text: s}); } query.callback(data); } }); $("#e12").select2({width: "resolve", tags:["red", "white", "purple", "orange", "yellow"]}); $("#e9").select2({width: 'resolve'}); //Rotten Tomatoes Infinite Scroll + Remote Data example $("#e7").select2({ placeholder: "Search for a movie", minimumInputLength: 3, width: 'resolve', ajax: { url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json", dataType: 'jsonp', quietMillis: 100, data: function (term, page) { // page is the one-based page number tracked by Select2 return { q: term, //search term page_limit: 10, // page size page: page, // page number apikey: "q7jnbsc56ysdyvvbeanghegk" // please do not use so this example keeps working }; }, results: function (data, page) { var more = (page * 10) < data.total; // whether or not there are more results available // notice we return the value of more so Select2 knows if more results can be loaded return {results: data.movies, more: more}; } }, formatResult: movieFormatResult, formatSelection: movieFormatSelection, dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results }); //MULTISELECT2 // For detailed documentatin, see: loudev.com $('#multi-select2').multiSelect(); $('#multi-select').multiSelect({ selectableHeader: "<input type='text' class='form-control' style='margin-bottom: 10px;' autocomplete='off' placeholder='Filter entries...'>", selectionHeader: "<input type='text' class='form-control' style='margin-bottom: 10px;' autocomplete='off' placeholder='Filter entries...'>", afterInit: function(ms){ var that = this, $selectableSearch = that.$selectableUl.prev(), $selectionSearch = that.$selectionUl.prev(), selectableSearchString = '#'+that.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)', selectionSearchString = '#'+that.$container.attr('id')+' .ms-elem-selection.ms-selected'; that.qs1 = $selectableSearch.quicksearch(selectableSearchString) .on('keydown', function(e){ if (e.which === 40){ that.$selectableUl.focus(); return false; } }); that.qs2 = $selectionSearch.quicksearch(selectionSearchString) .on('keydown', function(e){ if (e.which == 40){ that.$selectionUl.focus(); return false; } }); }, afterSelect: function(){ this.qs1.cache(); this.qs2.cache(); }, afterDeselect: function(){ this.qs1.cache(); this.qs2.cache(); } }); }); function movieFormatResult(movie) { var markup = "<table class='movie-result'><tr>"; if (movie.posters !== undefined && movie.posters.thumbnail !== undefined) { markup += "<td class='movie-image'><img src='" + movie.posters.thumbnail + "'/></td>"; } markup += "<td class='movie-info'><div class='movie-title'>" + movie.title + "</div>"; if (movie.critics_consensus !== undefined) { markup += "<div class='movie-synopsis'>" + movie.critics_consensus + "</div>"; } else if (movie.synopsis !== undefined) { markup += "<div class='movie-synopsis'>" + movie.synopsis + "</div>"; } markup += "</td></tr></table>" return markup; } function movieFormatSelection(movie) { return movie.title; }
JavaScript
$(function () { //Interacting with Data Points example var sin = [], cos = []; for (var i = 0; i < 14; i += 0.5) { sin.push([i, Math.sin(i) / i]); cos.push([i, Math.cos(i)]); } var plot = $.plot($("#sincos"), [{ data: sin, label: "sin(x)/x" }, { data: cos, label: "cos(x)" }], { series: { shadowSize: 0, lines: { show: true }, points: { show: true } }, grid: { hoverable: true, clickable: true}, yaxis: { min: -1.2, max: 1.2 }, colors: ["#539F2E", "#3C67A5"] }); function showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css({ position: 'absolute', display: 'none', top: y + 5, left: x + 5, border: '1px solid #fdd', padding: '2px', 'background-color': '#dfeffc', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#sincos").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y); } } else { $("#tooltip").remove(); previousPoint = null; } }); $("#sincos").bind("plotclick", function (event, pos, item) { if (item) { $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + "."); plot.highlight(item.series, item.datapoint); } }); //Multiple var d1 = []; for (var i = 0; i < 14; i += 0.5) d1.push([i, Math.sin(i)]); var d2 = [[0, 3], [4, 8], [8, 5], [9, 13]]; var d3 = []; for (var i = 0; i < 14; i += 0.5) d3.push([i, Math.cos(i)]); var d4 = []; for (var i = 0; i < 14; i += 0.1) d4.push([i, Math.sqrt(i * 10)]); var d5 = []; for (var i = 0; i < 14; i += 0.5) d5.push([i, Math.sqrt(i)]); var d6 = []; for (var i = 0; i < 14; i += 0.5 + Math.random()) d6.push([i, Math.sqrt(2*i + Math.sin(i) + 5)]); $.plot($("#multiple"), [ { data: d1, lines: { show: true, fill: true }, shadowSize: 0 }, { data: d2, bars: { show: true }, shadowSize: 0 }, { data: d3, points: { show: true }, shadowSize: 0 }, { data: d4, lines: { show: true }, shadowSize: 0 }, { data: d5, lines: { show: true }, points: { show: true }, shadowSize: 0 }, { data: d6, lines: { show: true, steps: true }, shadowSize: 0 } ]); // We use an inline data source in the example, usually data would // be fetched from a server var dxta = [], totalPoints = 300; var updateInterval = 30; function getRandomData() { if (dxta.length > 0) dxta = dxta.slice(1); // Do a random walk while (dxta.length < totalPoints) { var prev = dxta.length > 0 ? dxta[dxta.length - 1] : 50, y = prev + Math.random() * 10 - 5; if (y < 0) { y = 0; } else if (y > 100) { y = 100; } dxta.push(y); } // Zip the generated y values with the x values var res = []; for (var i = 0; i < dxta.length; ++i) { res.push([i, dxta[i]]) } return res; } var plot = $.plot("#realtime-updates", [ getRandomData() ], { series: { shadowSize: 0 // Drawing is faster without shadows }, yaxis: { min: 0, max: 100 }, xaxis: { show: false } }); function update() { plot.setData([getRandomData()]); // Since the axes don't change, we don't need to call plot.setupGrid() plot.draw(); setTimeout(update, updateInterval); } update(); var d1 = []; for (var i = 0; i <= 10; i += 1) { d1.push([i, parseInt(Math.random() * 30)]); } var d2 = []; for (var i = 0; i <= 10; i += 1) { d2.push([i, parseInt(Math.random() * 30)]); } var d3 = []; for (var i = 0; i <= 10; i += 1) { d3.push([i, parseInt(Math.random() * 30)]); } var stack = 0, bars = true, lines = false, steps = false; function plotWithOptions() { $.plot("#stacking", [ d1, d2, d3 ], { series: { stack: stack, lines: { show: lines, fill: true, steps: steps }, bars: { show: bars, barWidth: 0.6 } } }); } plotWithOptions(); $(".stackControls button").click(function (e) { e.preventDefault(); stack = $(this).text() == "With stacking" ? true : null; plotWithOptions(); }); $(".graphControls button").click(function (e) { e.preventDefault(); bars = $(this).text().indexOf("Bars") != -1; lines = $(this).text().indexOf("Lines") != -1; steps = $(this).text().indexOf("steps") != -1; plotWithOptions(); }); // data var data = [ { label: "Series1", data: 10}, { label: "Series2", data: 30}, { label: "Series3", data: 90}, { label: "Series4", data: 70}, { label: "Series5", data: 80}, { label: "Series6", data: 110} ]; var series = Math.floor(Math.random()*10)+1; for( var i = 0; i<series; i++) { data[i] = { label: "Series"+(i+1), data: Math.floor(Math.random()*100)+1 } } $.plot($("#graph0"), data, { series: { pie: { show: true } } }); // DONUT $.plot($("#donut"), data, { series: { pie: { innerRadius: 0.5, show: true } }, legend: { show: false } }); // INTERACTIVE $.plot($("#interactive"), data, { series: { pie: { show: true } }, grid: { hoverable: true, clickable: true }, legend: { show: false } }); $("#interactive").bind("plothover", pieHover); function pieHover(event, pos, obj) { if (!obj) return; percent = parseFloat(obj.series.percent).toFixed(2); $("#hover").html('<span style="font-weight: bold; color: '+obj.series.color+'">'+obj.series.label+' ('+percent+'%)</span>'); } });
JavaScript
$(document).ready(function(){ $("#demo").click(function(){ bootstro.start(".bootstro", { onComplete : function(params) { alert("Reached end of introduction with total " + (params.idx + 1)+ " slides"); }, onExit : function(params) { alert("Introduction stopped at slide #" + (params.idx + 1)); }, }); }); }); //<div class="col-md-4 bootstro" data-bootstro-title="I can align to [left,right,bottom,top]" data-bootstro-content="Simply because I am a popover. Specify me with &lt;b&gt;data-bootstro-placement&lt;/b&gt;" data-bootstro-placement="right" data-bootstro-width="400px" data-bootstro-step="3">
JavaScript
$(function() { //Parsley Form Validation //While the JS is not usually required in Parsley, we will be modifying //the default classes so it plays well with Bootstrap $('#validate-form').parsley({ successClass: 'has-success', errorClass: 'has-error', errors: { classHandler: function(el) { return $(el).closest('.form-group'); }, errorsWrapper: '<ul class=\"help-block list-unstyled\"></ul>', errorElem: '<li></li>' } }); });
JavaScript
$(function() { $('.mask').inputmask(); });
JavaScript
$(function(){ Morris.Line({ element: 'line-example', data: [ { y: '2006', a: 100, b: 90 }, { y: '2007', a: 75, b: 65 }, { y: '2008', a: 50, b: 40 }, { y: '2009', a: 75, b: 65 }, { y: '2010', a: 50, b: 40 }, { y: '2011', a: 75, b: 65 }, { y: '2012', a: 100, b: 90 } ], xkey: 'y', ykeys: ['a', 'b'], labels: ['Series A', 'Series B'] }); Morris.Bar({ element: 'bar-example', data: [ { y: '2006', a: 100, b: 90 }, { y: '2007', a: 75, b: 65 }, { y: '2008', a: 50, b: 40 }, { y: '2009', a: 75, b: 65 }, { y: '2010', a: 50, b: 40 }, { y: '2011', a: 75, b: 65 }, { y: '2012', a: 100, b: 90 } ], xkey: 'y', ykeys: ['a', 'b'], labels: ['Series A', 'Series B'] }); Morris.Donut({ element: 'donut-example', data: [ {label: "Download Sales", value: 12}, {label: "In-Store Sales", value: 30}, {label: "Mail-Order Sales", value: 20} ] }); Morris.Area({ element: 'area-example', data: [ { y: '2006', a: 100, b: 90 }, { y: '2007', a: 75, b: 65 }, { y: '2008', a: 50, b: 40 }, { y: '2009', a: 75, b: 65 }, { y: '2010', a: 50, b: 40 }, { y: '2011', a: 75, b: 65 }, { y: '2012', a: 100, b: 90 } ], xkey: 'y', ykeys: ['a', 'b'], labels: ['Series A', 'Series B'] }); });
JavaScript
$(document).ready(function() { //Load Wizards $('#basicwizard').stepy(); $('#wizard').stepy({finishButton: true, titleClick: true, block: true, validate: true}); //Add Wizard Compability - see docs $('.stepy-navigator').wrapInner('<div class="pull-right"></div>'); //Make Validation Compability - see docs $('#wizard').validate({ errorClass: "help-block", validClass: "help-block", highlight: function(element, errorClass,validClass) { $(element).closest('.form-group').addClass("has-error"); }, unhighlight: function(element, errorClass,validClass) { $(element).closest('.form-group').removeClass("has-error"); } }); });
JavaScript
$(function(){ var lineChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("line-chart").getContext("2d")).Line(lineChartData); var barChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", data : [28,48,40,19,96,27,100] } ] } var myLine = new Chart(document.getElementById("bar-chart").getContext("2d")).Bar(barChartData); var radarChartData = { labels : ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] } var myRadar = new Chart(document.getElementById("radar-chart").getContext("2d")).Radar(radarChartData,{scaleShowLabels : false, pointLabelFontSize : 10}); var pieData = [ { value: 30, color:"#F38630" }, { value : 50, color : "#E0E4CC" }, { value : 100, color : "#69D2E7" } ]; var myPie = new Chart(document.getElementById("pie-chart").getContext("2d")).Pie(pieData); var chartData = [ { value : Math.random(), color: "#D97041" }, { value : Math.random(), color: "#C7604C" }, { value : Math.random(), color: "#21323D" }, { value : Math.random(), color: "#9D9B7F" }, { value : Math.random(), color: "#7D4F6D" }, { value : Math.random(), color: "#584A5E" } ]; var myPolarArea = new Chart(document.getElementById("polar-area-chart").getContext("2d")).PolarArea(chartData); var doughnutData = [ { value: 30, color:"#F7464A" }, { value : 50, color : "#46BFBD" }, { value : 100, color : "#FDB45C" }, { value : 40, color : "#949FB1" }, { value : 120, color : "#4D5360" } ]; var myDoughnut = new Chart(document.getElementById("donut-chart").getContext("2d")).Doughnut(doughnutData); });
JavaScript
$(function(){ //Default $('#crop-default').Jcrop(); //Event Handler $('#crop-handler').Jcrop({ onChange: showCoords, onSelect: showCoords }); function showCoords(c) { $('#x1').val(c.x); $('#y1').val(c.y); $('#x2').val(c.x2); $('#y2').val(c.y2); $('#w').val(c.w); $('#h').val(c.h); }; });
JavaScript
// ------------------------------- // Demos // ------------------------------- $(document).ready( function() { $('.popovers').popover({container: 'body', trigger: 'hover', placement: 'top'}); //bootstrap's popover $('.tooltips').tooltip(); //bootstrap's tooltip $(".chathistory").niceScroll({horizrailenabled:false}); //chathistory scroll try { //Set nicescroll on notifications $(".scrollthis").niceScroll({horizrailenabled:false}); $('.dropdown').on('shown.bs.dropdown', function () { $(".scrollthis").getNiceScroll().resize(); $(".scrollthis").getNiceScroll().show(); }); $('.dropdown').on('hide.bs.dropdown', function () { $(".scrollthis").getNiceScroll().hide(); }); $(window).scroll(function(){ $(".scrollthis").getNiceScroll().resize(); }); } catch(e) {} prettyPrint(); //Apply Code Prettifier $('.toggle').toggles({on:true}); //EasyPieChart in rightbar try { $('.easypiechart#serverload').easyPieChart({ barColor: "#e73c3c", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'round', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); $('.easypiechart#ramusage').easyPieChart({ barColor: "#f39c12", trackColor: '#edeef0', scaleColor: '#d2d3d6', scaleLength: 5, lineCap: 'round', lineWidth: 2, size: 90, onStep: function(from, to, percent) { $(this.el).find('.percent').text(Math.round(percent)); } }); } catch(error) {} $("#currentbalance").sparkline([12700,8573,10145,21077,15380,14399,19158,23911,15401,16793,13115,23315], { type: 'bar', barColor: '#62bc1f', height: '45', barWidth: 7}); }); // ------------------------------- // Demo: Chatbar. // ------------------------------- $('.chatinput textarea').keypress(function (e) { if (e.which == 13) { var chatmsg = $(".chatinput textarea").val(); var oo=$(".chathistory").html(); var d=new Date(); var n=d.toLocaleTimeString(); if (!!$(".chatinput textarea").val()) $(".chathistory").html(oo+ "<div class='chatmsg'><p>"+chatmsg+"</p><span class='timestamp'>"+n+"</span></div>"); $(".chathistory").getNiceScroll().resize(); $(".chathistory").animate({ scrollTop: $(document).height() }, 0); $(this).val(''); // empty textarea return false; } }); // Toggle buttons $("a#hidechatbtn").click(function () { $("#widgetarea").toggle(); $("#chatarea").toggle(); }); $("#chatbar li a").click(function () { $("#widgetarea").toggle(); $("#chatarea").toggle(); }); // ------------------------------- // Show Theme Settings // ------------------------------- $('#slideitout').click(function() { $('#demo-theme-settings').toggleClass('shown'); return false; }); // ------------------------------- // Demo: Theme Settings // ------------------------------- // Demo Fixed Header if($.cookie('fixed-header') === 'navbar-static-top') { $('#fixedheader').toggles(); } else { $('#fixedheader').toggles({on:true}); } $('.dropdown-menu').on('click', function(e){ if($(this).hasClass('dropdown-menu-form')){ e.stopPropagation(); } }); $('#fixedheader').on('toggle', function (e, active) { $('header').toggleClass('navbar-fixed-top navbar-static-top'); $('body').toggleClass('static-header'); rightbarTopPos(); if (active) { $.removeCookie('fixed-header'); } else { $.cookie('fixed-header', 'navbar-static-top'); } }); // Demo Color Variation // Read the CSS files from data attributes $("#demo-color-variations a").click(function(){ $("head link#styleswitcher").attr("href", 'assets/demo/variations/' + $(this).data("theme")); $.cookie('theme',$(this).data("theme")); return false; }); $("#demo-header-variations a").click(function(){ $("head link#headerswitcher").attr("href", 'assets/demo/variations/' + $(this).data("headertheme")); $.cookie('headertheme',$(this).data("headertheme")); return false; }); //Demo Background Pattern $(".demo-blocks").click(function(){ $('.fixed-layout').css('background',$(this).css('background')); return false; });
JavaScript
jQuery(document).ready(function() { jQuery('#worldmap').vectorMap({ map: 'world_en', backgroundColor: 'transparent', color: '#f5f5f5', hoverOpacity: 0.7, selectedColor: '#0264d2', enableZoom: true, showTooltip: true, values: sample_data, scaleColors: ['#7cb4f2', '#1e80ee'], normalizeFunction: 'polynomial' }); jQuery('#usamap').vectorMap({ map: 'usa_en', backgroundColor: 'transparent', color: '#509BBD', hoverOpacity: 0.7, selectedColor: '#1278a6', enableZoom: true, showTooltip: true, values: sample_data, scaleColors: ['#C8EEFF', '#006491'], normalizeFunction: 'polynomial' }); jQuery('#euromap').vectorMap({ map: 'europe_en', backgroundColor: 'transparent', color: '#dddddd', hoverOpacity: 0.7, selectedColor: '#1dda1d', enableZoom: true, showTooltip: true, values: sample_data, scaleColors: ['#b6ddb7', '#51d951'], normalizeFunction: 'polynomial' }); });
JavaScript
/** Script: Slideshow.js Slideshow - A javascript class for Mootools to stream and animate the presentation of images on your website. License: MIT-style license. Copyright: Copyright (c) 2008 [Aeron Glemann](http://www.electricprism.com/aeron/). Dependencies: Mootools 1.2 Core: Fx.Morph, Fx.Tween, Selectors, Element.Dimensions. Mootools 1.2 More: Assets. */ Slideshow = new Class({ Implements: [Chain, Events, Options], options: {/* onComplete: $empty, onEnd: $empty, onStart: $empty,*/ captions: true, center: true, classes: [], controller: false, delay: 2000, duration: 1500, fast: false, height: false, href: '', hu: '', linked: false, loader: {'animate': ['css/loader-#.png', 12]}, loop: true, match: /\?slide=(\d+)$/, overlap: true, paused: false, properties: ['href', 'rel', 'rev', 'title'], random: false, replace: [/(\.[^\.]+)$/, 't$1'], resize: 'width', slide: 0, thumbnails: false, titles: true, transition: function(p){return -(Math.cos(Math.PI * p) - 1) / 2;}, width: false }, /** Constructor: initialize Creates an instance of the Slideshow class. Arguments: element - (element) The wrapper element. data - (array or object) The images and optional thumbnails, captions and links for the show. options - (object) The options below. Syntax: var myShow = new Slideshow(element, data, options); */ initialize: function(el, data, options){ this.setOptions(options); this.slideshow = $(el); if (!this.slideshow) return; this.slideshow.set('styles', {'display': 'block', 'position': 'relative', 'z-index': 0}); var match = window.location.href.match(this.options.match); this.slide = (this.options.match && match) ? match[1].toInt() : this.options.slide; this.counter = this.delay = this.transition = 0; this.direction = 'left'; this.paused = false; if (!this.options.overlap) this.options.duration *= 2; var anchor = this.slideshow.getElement('a') || new Element('a'); if (!this.options.href) this.options.href = anchor.get('href') || ''; if (this.options.hu.length && !this.options.hu.test(/\/$/)) this.options.hu += '/'; if (this.options.fast === true) this.options.fast = 2; // styles var keys = ['slideshow', 'first', 'prev', 'play', 'pause', 'next', 'last', 'images', 'captions', 'controller', 'thumbnails', 'hidden', 'visible', 'inactive', 'active', 'loader']; var values = keys.map(function(key, i){ return this.options.classes[i] || key; }, this); this.classes = values.associate(keys); this.classes.get = function(){ var str = '.' + this.slideshow; for (var i = 0, l = arguments.length; i < l; i++) str += ('-' + this[arguments[i]]); return str; }.bind(this.classes); // data if (!data){ this.options.hu = ''; data = {}; var thumbnails = this.slideshow.getElements(this.classes.get('thumbnails') + ' img'); this.slideshow.getElements(this.classes.get('images') + ' img').each(function(img, i){ var src = img.get('src'); var caption = $pick(img.get('alt'), img.get('title'), ''); var parent = img.getParent(); var properties = (parent.get('tag') == 'a') ? parent.getProperties : {}; var href = img.getParent().get('href') || ''; var thumbnail = (thumbnails[i]) ? thumbnails[i].get('src') : ''; data[src] = {'caption': caption, 'href': href, 'thumbnail': thumbnail}; }); } var loaded = this.load(data); if (!loaded) return; // events this.events = $H({'keydown': [], 'keyup': [], 'mousemove': []}); var keyup = function(e){ switch(e.key){ case 'left': this.prev(e.shift); break; case 'right': this.next(e.shift); break; case 'p': this.pause(); break; } }.bind(this); this.events.keyup.push(keyup); document.addEvent('keyup', keyup); // required elements var el = this.slideshow.getElement(this.classes.get('images')); var images = (el) ? el.empty() : new Element('div', {'class': this.classes.get('images').substr(1)}).inject(this.slideshow); var div = images.getSize(); this.height = this.options.height || div.y; this.width = this.options.width || div.x; images.set({'styles': {'display': 'block', 'height': this.height, 'overflow': 'hidden', 'position': 'relative', 'width': this.width}}); this.slideshow.store('images', images); this.a = this.image = this.slideshow.getElement('img') || new Element('img'); if (Browser.Engine.trident && Browser.Engine.version > 4) this.a.style.msInterpolationMode = 'bicubic'; this.a.set('styles', {'display': 'none', 'position': 'absolute', 'zIndex': 1}); this.b = this.a.clone(); [this.a, this.b].each(function(img){ anchor.clone().cloneEvents(anchor).grab(img).inject(images); }); // optional elements if (this.options.captions) this._captions(); if (this.options.controller) this._controller(); if (this.options.loader) this._loader(); if (this.options.thumbnails) this._thumbnails(); // begin show this._preload(); }, /** Public method: go Jump directly to a slide in the show. Arguments: n - (integer) The index number of the image to jump to, 0 being the first image in the show. Syntax: myShow.go(n); */ go: function(n, direction){ if ((this.slide - 1 + this.data.images.length) % this.data.images.length == n || $time() < this.transition) return; $clear(this.timer); this.delay = 0; this.direction = (direction) ? direction : ((n < this.slide) ? 'right' : 'left'); this.slide = n; if (this.preloader) this.preloader = this.preloader.destroy(); this._preload(this.options.fast == 2 || (this.options.fast == 1 && this.paused)); }, /** Public method: first Goes to the first image in the show. Syntax: myShow.first(); */ first: function(){ this.prev(true); }, /** Public method: prev Goes to the previous image in the show. Syntax: myShow.prev(); */ prev: function(first){ var n = 0; if (!first){ if (this.options.random){ // if it's a random show get the previous slide from the showed array if (this.showed.i < 2) return; this.showed.i -= 2; n = this.showed.array[this.showed.i]; } else n = (this.slide - 2 + this.data.images.length) % this.data.images.length; } this.go(n, 'right'); }, /** Public method: pause Toggles play / pause state of the show. Arguments: p - (undefined, 1 or 0) Call pause with no arguments to toggle the pause state. Call pause(1) to force pause, or pause(0) to force play. Syntax: myShow.pause(p); */ pause: function(p){ if ($chk(p)) this.paused = (p) ? false : true; if (this.paused){ this.paused = false; this.delay = this.transition = 0; this.timer = this._preload.delay(100, this); [this.a, this.b].each(function(img){ ['morph', 'tween'].each(function(p){ if (this.retrieve(p)) this.get(p).resume(); }, img); }); if (this.options.controller) this.slideshow.getElement('.' + this.classes.pause).removeClass(this.classes.play); } else { this.paused = true; this.delay = Number.MAX_VALUE; this.transition = 0; $clear(this.timer); [this.a, this.b].each(function(img){ ['morph', 'tween'].each(function(p){ if (this.retrieve(p)) this.get(p).pause(); }, img); }); if (this.options.controller) this.slideshow.getElement('.' + this.classes.pause).addClass(this.classes.play); } }, /** Public method: next Goes to the next image in the show. Syntax: myShow.next(); */ next: function(last){ var n = (last) ? this.data.images.length - 1 : this.slide; this.go(n, 'left'); }, /** Public method: last Goes to the last image in the show. Syntax: myShow.last(); */ last: function(){ this.next(true); }, /** Public method: load Loads a new data set into the show: will stop the current show, rewind and rebuild thumbnails if applicable. Arguments: data - (array or object) The images and optional thumbnails, captions and links for the show. Syntax: myShow.load(data); */ load: function(data){ this.firstrun = true; this.showed = {'array': [], 'i': 0}; if ($type(data) == 'array'){ this.options.captions = false; data = new Array(data.length).associate(data.map(function(image, i){ return image + '?' + i })); } this.data = {'images': [], 'captions': [], 'hrefs': [], 'thumbnails': []}; for (var image in data){ var obj = data[image] || {}; var caption = (obj.caption) ? obj.caption.trim() : ''; var href = (obj.href) ? obj.href.trim() : ((this.options.linked) ? this.options.hu + image : this.options.href); var thumbnail = (obj.thumbnail) ? obj.thumbnail.trim() : image.replace(this.options.replace[0], this.options.replace[1]); this.data.images.push(image); this.data.captions.push(caption); this.data.hrefs.push(href); this.data.thumbnails.push(thumbnail); } if (this.options.random) this.slide = $random(0, this.data.images.length - 1); // only run when data is loaded dynamically into an existing slideshow instance if (this.options.thumbnails && this.slideshow.retrieve('thumbnails')) this._thumbnails(); if (this.slideshow.retrieve('images')){ [this.a, this.b].each(function(img){ ['morph', 'tween'].each(function(p){ if (this.retrieve(p)) this.get(p).cancel(); }, img); }); this.slide = this.transition = 0; this.go(0); } return this.data.images.length; }, /** Public method: destroy Destroys a Slideshow instance. Arguments: p - (string) The images and optional thumbnails, captions and links for the show. Syntax: myShow.destroy(p); */ destroy: function(p){ this.events.each(function(array, e){ array.each(function(fn){ document.removeEvent(e, fn); }); }); this.pause(1); if (this.options.loader) $clear(this.slideshow.retrieve('loader').retrieve('timer')); if (this.options.thumbnails) $clear(this.slideshow.retrieve('thumbnails').retrieve('timer')); this.slideshow.uid = Native.UID++; if (p) this.slideshow[p](); }, /** Private method: preload Preloads the next slide in the show, once loaded triggers the show, updates captions, thumbnails, etc. */ _preload: function(fast){ if (!this.preloader) this.preloader = new Asset.image(this.options.hu + this.data.images[this.slide], {'onload': function(){ this.store('loaded', true); }}); if (this.preloader.retrieve('loaded') && $time() > this.delay && $time() > this.transition){ if (this.stopped){ if (this.options.captions) this.slideshow.retrieve('captions').get('morph').cancel().start(this.classes.get('captions', 'hidden')); this.pause(1); if (this.end) this.fireEvent('end'); this.stopped = this.end = false; return; } this.image = (this.counter % 2) ? this.b : this.a; this.image.set('styles', {'display': 'block', 'height': 'auto', 'visibility': 'hidden', 'width': 'auto', 'zIndex': this.counter}); ['src', 'height', 'width'].each(function(prop){ this.image.set(prop, this.preloader.get(prop)); }, this); this._resize(this.image); this._center(this.image); var anchor = this.image.getParent(); if (this.data.hrefs[this.slide]) anchor.set('href', this.data.hrefs[this.slide]); else anchor.erase('href'); var text = (this.data.captions[this.slide]) ? this.data.captions[this.slide].replace(/<.+?>/gm, '').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, "'") : ''; this.image.set('alt', text); if (this.options.titles) anchor.set('title', text); if (this.options.loader) this.slideshow.retrieve('loader').fireEvent('hide'); if (this.options.captions) this.slideshow.retrieve('captions').fireEvent('update', fast); if (this.options.thumbnails) this.slideshow.retrieve('thumbnails').fireEvent('update', fast); this._show(fast); this._loaded(); } else { if ($time() > this.delay && this.options.loader) this.slideshow.retrieve('loader').fireEvent('show'); this.timer = (this.paused && this.preloader.retrieve('loaded')) ? null : this._preload.delay(100, this, fast); } }, /** Private method: show Does the slideshow effect. */ _show: function(fast){ if (!this.image.retrieve('morph')){ var options = (this.options.overlap) ? {'duration': this.options.duration, 'link': 'cancel'} : {'duration': this.options.duration / 2, 'link': 'chain'}; $$(this.a, this.b).set('morph', $merge(options, {'onStart': this._start.bind(this), 'onComplete': this._complete.bind(this), 'transition': this.options.transition})); } var hidden = this.classes.get('images', ((this.direction == 'left') ? 'next' : 'prev')); var visible = this.classes.get('images', 'visible'); var img = (this.counter % 2) ? this.a : this.b; if (fast){ img.get('morph').cancel().set(hidden); this.image.get('morph').cancel().set(visible); } else { if (this.options.overlap){ img.get('morph').set(visible); this.image.get('morph').set(hidden).start(visible); } else { var fn = function(hidden, visible){ this.image.get('morph').set(hidden).start(visible); }.pass([hidden, visible], this); hidden = this.classes.get('images', ((this.direction == 'left') ? 'prev' : 'next')); img.get('morph').set(visible).start(hidden).chain(fn); } } }, /** Private method: loaded Run after the current image has been loaded, sets up the next image to be shown. */ _loaded: function(){ this.counter++; this.delay = (this.paused) ? Number.MAX_VALUE : $time() + this.options.duration + this.options.delay; this.direction = 'left'; this.transition = (this.options.fast == 2 || (this.options.fast == 1 && this.paused)) ? 0 : $time() + this.options.duration; if (this.slide + 1 == this.data.images.length && !this.options.loop && !this.options.random) this.stopped = this.end = true; if (this.options.random){ this.showed.i++; if (this.showed.i >= this.showed.array.length){ var n = this.slide; if (this.showed.array.getLast() != n) this.showed.array.push(n); while (this.slide == n) this.slide = $random(0, this.data.images.length - 1); } else this.slide = this.showed.array[this.showed.i]; } else this.slide = (this.slide + 1) % this.data.images.length; if (this.image.getStyle('visibility') != 'visible') (function(){ this.image.setStyle('visibility', 'visible'); }).delay(1, this); if (this.preloader) this.preloader = this.preloader.destroy(); this._preload(); }, /** Private method: center Center an image. */ _center: function(img){ if (this.options.center){ var size = img.getSize(); img.set('styles', {'left': (size.x - this.width) / -2, 'top': (size.y - this.height) / -2}); } }, /** Private method: resize Resizes an image. */ _resize: function(img){ if (this.options.resize){ var h = this.preloader.get('height'), w = this.preloader.get('width'); var dh = this.height / h, dw = this.width / w, d; if (this.options.resize == 'length') d = (dh > dw) ? dw : dh; else d = (dh > dw) ? dh : dw; img.set('styles', {height: Math.ceil(h * d), width: Math.ceil(w * d)}); } }, /** Private method: start Callback on start of slide change. */ _start: function(){ this.fireEvent('start'); }, /** Private method: complete Callback on start of slide change. */ _complete: function(){ if (this.firstrun && this.options.paused){ this.firstrun = false; this.pause(1); } this.fireEvent('complete'); }, /** Private method: captions Builds the optional caption element, adds interactivity. This method can safely be removed if the captions option is not enabled. */ _captions: function(){ if (this.options.captions === true) this.options.captions = {}; var el = this.slideshow.getElement(this.classes.get('captions')); var captions = (el) ? el.empty() : new Element('div', {'class': this.classes.get('captions').substr(1)}).inject(this.slideshow); captions.set({ 'events': { 'update': function(fast){ var captions = this.slideshow.retrieve('captions'); var empty = (this.data.captions[this.slide] === ''); if (fast){ var p = (empty) ? 'hidden' : 'visible'; captions.set('html', this.data.captions[this.slide]).get('morph').cancel().set(this.classes.get('captions', p)); } else { var fn = (empty) ? $empty : function(n){ this.slideshow.retrieve('captions').set('html', this.data.captions[n]).morph(this.classes.get('captions', 'visible')) }.pass(this.slide, this); captions.get('morph').cancel().start(this.classes.get('captions', 'hidden')).chain(fn); } }.bind(this) }, 'morph': $merge(this.options.captions, {'link': 'chain'}) }); this.slideshow.store('captions', captions); }, /** Private method: controller Builds the optional controller element, adds interactivity. This method can safely be removed if the controller option is not enabled. */ _controller: function(){ if (this.options.controller === true) this.options.controller = {}; var el = this.slideshow.getElement(this.classes.get('controller')); var controller = (el) ? el.empty() : new Element('div', {'class': this.classes.get('controller').substr(1)}).inject(this.slideshow); var ul = new Element('ul').inject(controller); $H({'first': 'Shift + Leftwards Arrow', 'prev': 'Leftwards Arrow', 'pause': 'P', 'next': 'Rightwards Arrow', 'last': 'Shift + Rightwards Arrow'}).each(function(accesskey, action){ var li = new Element('li', { 'class': (action == 'pause' && this.options.paused) ? this.classes.play + ' ' + this.classes[action] : this.classes[action] }).inject(ul); var a = this.slideshow.retrieve(action, new Element('a', { 'title': ((action == 'pause') ? this.classes.play.capitalize() + ' / ' : '') + this.classes[action].capitalize() + ' [' + accesskey + ']' }).inject(li)); a.set('events', { 'click': function(action){this[action]();}.pass(action, this), 'mouseenter': function(active){this.addClass(active);}.pass(this.classes.active, a), 'mouseleave': function(active){this.removeClass(active);}.pass(this.classes.active, a) }); }, this); controller.set({ 'events': { 'hide': function(hidden){ if (!this.retrieve('hidden')) this.store('hidden', true).morph(hidden); }.pass(this.classes.get('controller', 'hidden'), controller), 'show': function(visible){ if (this.retrieve('hidden')) this.store('hidden', false).morph(visible); }.pass(this.classes.get('controller', 'visible'), controller) }, 'morph': $merge(this.options.controller, {'link': 'cancel'}) }).store('hidden', false); var keydown = function(e){ if (['left', 'right', 'p'].contains(e.key)){ var controller = this.slideshow.retrieve('controller'); if (controller.retrieve('hidden')) controller.get('morph').set(this.classes.get('controller', 'visible')); switch(e.key){ case 'left': this.slideshow.retrieve((e.shift) ? 'first' : 'prev').fireEvent('mouseenter'); break; case 'right': this.slideshow.retrieve((e.shift) ? 'last' : 'next').fireEvent('mouseenter'); break; default: this.slideshow.retrieve('pause').fireEvent('mouseenter'); break; } } }.bind(this); this.events.keydown.push(keydown); var keyup = function(e){ if (['left', 'right', 'p'].contains(e.key)){ var controller = this.slideshow.retrieve('controller'); if (controller.retrieve('hidden')) controller.store('hidden', false).fireEvent('hide'); switch(e.key){ case 'left': this.slideshow.retrieve((e.shift) ? 'first' : 'prev').fireEvent('mouseleave'); break; case 'right': this.slideshow.retrieve((e.shift) ? 'last' : 'next').fireEvent('mouseleave'); break; default: this.slideshow.retrieve('pause').fireEvent('mouseleave'); break; } } }.bind(this); this.events.keyup.push(keyup); var mousemove = function(e){ var images = this.slideshow.retrieve('images').getCoordinates(); if (e.page.x > images.left && e.page.x < images.right && e.page.y > images.top && e.page.y < images.bottom) this.slideshow.retrieve('controller').fireEvent('show'); else this.slideshow.retrieve('controller').fireEvent('hide'); }.bind(this); this.events.mousemove.push(mousemove); document.addEvents({'keydown': keydown, 'keyup': keyup, 'mousemove': mousemove}); this.slideshow.retrieve('controller', controller).fireEvent('hide'); }, /** Private method: loader Builds the optional loader element, adds interactivity. This method can safely be removed if the loader option is not enabled. */ _loader: function(){ if (this.options.loader === true) this.options.loader = {}; var loader = new Element('div', { 'class': this.classes.get('loader').substr(1), 'morph': $merge(this.options.loader, {'link': 'cancel'}) }).store('hidden', false).store('i', 1).inject(this.slideshow.retrieve('images')); if (this.options.loader.animate){ for (var i = 0; i < this.options.loader.animate[1]; i++) img = new Asset.image(this.options.loader.animate[0].replace(/#/, i)); if (Browser.Engine.trident4 && this.options.loader.animate[0].contains('png')) loader.setStyle('backgroundImage', 'none'); } loader.set('events', { 'animate': function(){ var loader = this.slideshow.retrieve('loader'); var i = (loader.retrieve('i').toInt() + 1) % this.options.loader.animate[1]; loader.store('i', i); var img = this.options.loader.animate[0].replace(/#/, i); if (Browser.Engine.trident4 && this.options.loader.animate[0].contains('png')) loader.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + img + '", sizingMethod="scale")'; else loader.setStyle('backgroundImage', 'url(' + img + ')'); }.bind(this), 'hide': function(){ var loader = this.slideshow.retrieve('loader'); if (!loader.retrieve('hidden')){ loader.store('hidden', true).morph(this.classes.get('loader', 'hidden')); if (this.options.loader.animate) $clear(loader.retrieve('timer')); } }.bind(this), 'show': function(){ var loader = this.slideshow.retrieve('loader'); if (loader.retrieve('hidden')){ loader.store('hidden', false).morph(this.classes.get('loader', 'visible')); if (this.options.loader.animate) loader.store('timer', function(){this.fireEvent('animate');}.periodical(50, loader)); } }.bind(this) }); this.slideshow.retrieve('loader', loader).fireEvent('hide'); }, /** Private method: thumbnails Builds the optional thumbnails element, adds interactivity. This method can safely be removed if the thumbnails option is not enabled. */ _thumbnails: function(){ if (this.options.thumbnails === true) this.options.thumbnails = {}; var el = this.slideshow.getElement(this.classes.get('thumbnails')); var thumbnails = (el) ? el.empty() : new Element('div', {'class': this.classes.get('thumbnails').substr(1)}).inject(this.slideshow); thumbnails.setStyle('overflow', 'hidden'); var ul = new Element('ul', {'tween': {'link': 'cancel'}}).inject(thumbnails); this.data.thumbnails.each(function(thumbnail, i){ var li = new Element('li').inject(ul); var a = new Element('a', { 'events': { 'click': function(i){ this.go(i); return false; }.pass(i, this), 'loaded': function(){ this.data.thumbnails.pop(); if (!this.data.thumbnails.length){ var div = thumbnails.getCoordinates(); var props = thumbnails.retrieve('props'); var limit = 0, pos = props[1], size = props[2]; thumbnails.getElements('li').each(function(li){ var li = li.getCoordinates(); if (li[pos] > limit) limit = li[pos]; }, this); thumbnails.store('limit', div[size] + div[props[0]] - limit); } }.bind(this) }, 'href': this.options.hu + this.data.images[i], 'morph': $merge(this.options.thumbnails, {'link': 'cancel'}) }).inject(li); if (this.data.captions[i] && this.options.titles) a.set('title', this.data.captions[i].replace(/<.+?>/gm, '').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, "'")); var img = new Asset.image(this.options.hu + thumbnail, { 'onload': function(){this.fireEvent('loaded');}.bind(a) }).inject(a); }, this); thumbnails.set('events', { 'scroll': function(n, fast){ var div = this.getCoordinates(); var ul = this.getElement('ul').getPosition(); var props = this.retrieve('props'); var axis = props[3], delta, pos = props[0], size = props[2], value; var tween = this.getElement('ul').get('tween', {'property': pos}); if ($chk(n)){ var li = this.getElements('li')[n].getCoordinates(); delta = div[pos] + (div[size] / 2) - (li[size] / 2) - li[pos] value = (ul[axis] - div[pos] + delta).limit(this.retrieve('limit'), 0); if (fast) tween.set(value); else tween.start(value); } else{ var area = div[props[2]] / 3, page = this.retrieve('page'), velocity = -0.2; if (page[axis] < (div[pos] + area)) delta = (page[axis] - div[pos] - area) * velocity; else if (page[axis] > (div[pos] + div[size] - area)) delta = (page[axis] - div[pos] - div[size] + area) * velocity; if (delta){ value = (ul[axis] - div[pos] + delta).limit(this.retrieve('limit'), 0); tween.set(value); } } }.bind(thumbnails), 'update': function(fast){ var thumbnails = this.slideshow.retrieve('thumbnails'); thumbnails.getElements('a').each(function(a, i){ if (i == this.slide){ if (!a.retrieve('active', false)){ a.store('active', true); var active = this.classes.get('thumbnails', 'active'); if (fast) a.get('morph').set(active); else a.morph(active); } } else { if (a.retrieve('active', true)){ a.store('active', false); var inactive = this.classes.get('thumbnails', 'inactive'); if (fast) a.get('morph').set(inactive); else a.morph(inactive); } } }, this); if (!thumbnails.retrieve('mouseover')) thumbnails.fireEvent('scroll', [this.slide, fast]); }.bind(this) }) var div = thumbnails.getCoordinates(); thumbnails.store('props', (div.height > div.width) ? ['top', 'bottom', 'height', 'y'] : ['left', 'right', 'width', 'x']); var mousemove = function(e){ var div = this.getCoordinates(); if (e.page.x > div.left && e.page.x < div.right && e.page.y > div.top && e.page.y < div.bottom){ this.store('page', e.page); if (!this.retrieve('mouseover')){ this.store('mouseover', true); this.store('timer', function(){this.fireEvent('scroll');}.periodical(50, this)); } } else { if (this.retrieve('mouseover')){ this.store('mouseover', false); $clear(this.retrieve('timer')); } } }.bind(thumbnails); this.events.mousemove.push(mousemove); document.addEvent('mousemove', mousemove); this.slideshow.store('thumbnails', thumbnails); } });
JavaScript
// ----------------------------------------------------------------------------------- // // Lightbox v2.04 // by Lokesh Dhakar - http://www.lokeshdhakar.com // Last Modification: 2/9/08 // // For more information, visit: // http://lokeshdhakar.com/projects/lightbox2/ // // Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/ // - Free for use in both personal and commercial projects // - Attribution requires leaving author name, author link, and the license info intact. // // Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets. // Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous. // // ----------------------------------------------------------------------------------- /* Table of Contents ----------------- Configuration Lightbox Class Declaration - initialize() - updateImageList() - start() - changeImage() - resizeImageContainer() - showImage() - updateDetails() - updateNav() - enableKeyboardNav() - disableKeyboardNav() - keyboardAction() - preloadNeighborImages() - end() Function Calls - document.observe() */ // ----------------------------------------------------------------------------------- // // Configurationl // LightboxOptions = Object.extend({ fileLoadingImage: 'images/loading.gif', fileBottomNavCloseImage: 'images/closelabel.gif', overlayOpacity: 0.8, // controls transparency of shadow overlay animate: true, // toggles resizing animations resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest) borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable // When grouping images this is used to write: Image # of #. // Change it for non-english localization labelImage: "Image", labelOf: "of" }, window.LightboxOptions || {}); // ----------------------------------------------------------------------------------- var Lightbox = Class.create(); Lightbox.prototype = { imageArray: [], activeImage: undefined, // initialize() // Constructor runs on completion of the DOM loading. Calls updateImageList and then // the function inserts html at the bottom of the page which is used to display the shadow // overlay and the image container. // initialize: function() { this.updateImageList(); this.keyboardAction = this.keyboardAction.bindAsEventListener(this); if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10; if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1; this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0; this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension. // If animations are turned off, it will be hidden as to prevent a flicker of a // white 250 by 250 box. var size = (LightboxOptions.animate ? 250 : 1) + 'px'; // Code inserts html at the bottom of the page that looks similar to this: // // <div id="overlay"></div> // <div id="lightbox"> // <div id="outerImageContainer"> // <div id="imageContainer"> // <img id="lightboxImage"> // <div style="" id="hoverNav"> // <a href="#" id="prevLink"></a> // <a href="#" id="nextLink"></a> // </div> // <div id="loading"> // <a href="#" id="loadingLink"> // <img src="images/loading.gif"> // </a> // </div> // </div> // </div> // <div id="imageDataContainer"> // <div id="imageData"> // <div id="imageDetails"> // <span id="caption"></span> // <span id="numberDisplay"></span> // </div> // <div id="bottomNav"> // <a href="#" id="bottomNavClose"> // <img src="images/close.gif"> // </a> // </div> // </div> // </div> // </div> var objBody = $$('body')[0]; objBody.appendChild(Builder.node('div',{id:'overlay'})); objBody.appendChild(Builder.node('div',{id:'lightbox'}, [ Builder.node('div',{id:'outerImageContainer'}, Builder.node('div',{id:'imageContainer'}, [ Builder.node('img',{id:'lightboxImage'}), Builder.node('div',{id:'hoverNav'}, [ Builder.node('a',{id:'prevLink', href: '#' }), Builder.node('a',{id:'nextLink', href: '#' }) ]), Builder.node('div',{id:'loading'}, Builder.node('a',{id:'loadingLink', href: '#' }, Builder.node('img', {src: LightboxOptions.fileLoadingImage}) ) ) ]) ), Builder.node('div', {id:'imageDataContainer'}, Builder.node('div',{id:'imageData'}, [ Builder.node('div',{id:'imageDetails'}, [ Builder.node('span',{id:'caption'}), Builder.node('span',{id:'numberDisplay'}) ]), Builder.node('div',{id:'bottomNav'}, Builder.node('a',{id:'bottomNavClose', href: '#' }, Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage }) ) ) ]) ) ])); $('overlay').hide().observe('click', (function() { this.end(); }).bind(this)); $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this)); $('outerImageContainer').setStyle({ width: size, height: size }); $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this)); $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this)); $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this)); var th = this; (function(){ var ids = 'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose'; $w(ids).each(function(id){ th[id] = $(id); }); }).defer(); }, // // updateImageList() // Loops through anchor tags looking for 'lightbox' references and applies onclick // events to appropriate links. You can rerun after dynamically adding images w/ajax. // updateImageList: function() { this.updateImageList = Prototype.emptyFunction; document.observe('click', (function(event){ var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]'); if (target) { event.stop(); this.start(target); } }).bind(this)); }, // // start() // Display overlay and lightbox. If image is part of a set, add siblings to imageArray. // start: function(imageLink) { $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' }); // stretch overlay to fill page and fade in var arrayPageSize = this.getPageSize(); $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' }); new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity }); this.imageArray = []; var imageNum = 0; if ((imageLink.rel == 'lightbox')){ // if image is NOT part of a set, add single image to imageArray this.imageArray.push([imageLink.href, imageLink.title]); } else { // if image is part of a set.. this.imageArray = $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]'). collect(function(anchor){ return [anchor.href, anchor.title]; }). uniq(); while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; } } // calculate top and left offset for the lightbox var arrayPageScroll = document.viewport.getScrollOffsets(); var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10); var lightboxLeft = arrayPageScroll[0]; this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show(); this.changeImage(imageNum); }, // // changeImage() // Hide most elements and preload image in preparation for resizing image container. // changeImage: function(imageNum) { this.activeImage = imageNum; // update global var // hide elements during transition if (LightboxOptions.animate) this.loading.show(); this.lightboxImage.hide(); this.hoverNav.hide(); this.prevLink.hide(); this.nextLink.hide(); // HACK: Opera9 does not currently support scriptaculous opacity and appear fx this.imageDataContainer.setStyle({opacity: .0001}); this.numberDisplay.hide(); var imgPreloader = new Image(); // once image is preloaded, resize image container imgPreloader.onload = (function(){ this.lightboxImage.src = this.imageArray[this.activeImage][0]; this.resizeImageContainer(imgPreloader.width, imgPreloader.height); }).bind(this); imgPreloader.src = this.imageArray[this.activeImage][0]; }, // // resizeImageContainer() // resizeImageContainer: function(imgWidth, imgHeight) { // get current width and height var widthCurrent = this.outerImageContainer.getWidth(); var heightCurrent = this.outerImageContainer.getHeight(); // get new width and height var widthNew = (imgWidth + LightboxOptions.borderSize * 2); var heightNew = (imgHeight + LightboxOptions.borderSize * 2); // scalars based on change from old to new var xScale = (widthNew / widthCurrent) * 100; var yScale = (heightNew / heightCurrent) * 100; // calculate size difference between new and old image, and resize if necessary var wDiff = widthCurrent - widthNew; var hDiff = heightCurrent - heightNew; if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); // if new and old image are same size and no scaling transition is necessary, // do a quick pause to prevent image flicker. var timeout = 0; if ((hDiff == 0) && (wDiff == 0)){ timeout = 100; if (Prototype.Browser.IE) timeout = 250; } (function(){ this.prevLink.setStyle({ height: imgHeight + 'px' }); this.nextLink.setStyle({ height: imgHeight + 'px' }); this.imageDataContainer.setStyle({ width: widthNew + 'px' }); this.showImage(); }).bind(this).delay(timeout / 1000); }, // // showImage() // Display image and begin preloading neighbors. // showImage: function(){ this.loading.hide(); new Effect.Appear(this.lightboxImage, { duration: this.resizeDuration, queue: 'end', afterFinish: (function(){ this.updateDetails(); }).bind(this) }); this.preloadNeighborImages(); }, // // updateDetails() // Display caption, image number, and bottom nav. // updateDetails: function() { // if caption is not null if (this.imageArray[this.activeImage][1] != ""){ this.caption.update(this.imageArray[this.activeImage][1]).show(); } // if image is part of set display 'Image x of x' if (this.imageArray.length > 1){ this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show(); } new Effect.Parallel( [ new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) ], { duration: this.resizeDuration, afterFinish: (function() { // update overlay size and update nav var arrayPageSize = this.getPageSize(); this.overlay.setStyle({ height: arrayPageSize[1] + 'px' }); this.updateNav(); }).bind(this) } ); }, // // updateNav() // Display appropriate previous and next hover navigation. // updateNav: function() { this.hoverNav.show(); // if not first image in set, display prev image button if (this.activeImage > 0) this.prevLink.show(); // if not last image in set, display next image button if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show(); this.enableKeyboardNav(); }, // // enableKeyboardNav() // enableKeyboardNav: function() { document.observe('keydown', this.keyboardAction); }, // // disableKeyboardNav() // disableKeyboardNav: function() { document.stopObserving('keydown', this.keyboardAction); }, // // keyboardAction() // keyboardAction: function(event) { var keycode = event.keyCode; var escapeKey; if (event.DOM_VK_ESCAPE) { // mozilla escapeKey = event.DOM_VK_ESCAPE; } else { // ie escapeKey = 27; } var key = String.fromCharCode(keycode).toLowerCase(); if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox this.end(); } else if ((key == 'p') || (keycode == 37)){ // display previous image if (this.activeImage != 0){ this.disableKeyboardNav(); this.changeImage(this.activeImage - 1); } } else if ((key == 'n') || (keycode == 39)){ // display next image if (this.activeImage != (this.imageArray.length - 1)){ this.disableKeyboardNav(); this.changeImage(this.activeImage + 1); } } }, // // preloadNeighborImages() // Preload previous and next images. // preloadNeighborImages: function(){ var preloadNextImage, preloadPrevImage; if (this.imageArray.length > this.activeImage + 1){ preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeImage + 1][0]; } if (this.activeImage > 0){ preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeImage - 1][0]; } }, // // end() // end: function() { this.disableKeyboardNav(); this.lightbox.hide(); new Effect.Fade(this.overlay, { duration: this.overlayDuration }); $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' }); }, // // getPageSize() // getPageSize: function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if(xScroll < windowWidth){ pageWidth = xScroll; } else { pageWidth = windowWidth; } return [pageWidth,pageHeight]; } } document.observe('dom:loaded', function () { new Lightbox(); });
JavaScript
// script.aculo.us scriptaculous.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.8.1', require: function(libraryName) { // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); }, REQUIRED_PROTOTYPE: '1.6.0', load: function() { function convertVersionString(versionString){ var r = versionString.split('.'); return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]); } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); $A(document.getElementsByTagName("script")).findAll( function(s) { return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/)) }).each( function(s) { var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,''); var includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } } Scriptaculous.load();
JavaScript
/** * hoverIntent is similar to jQuery's built-in "hover" function except that * instead of firing the onMouseOver event immediately, hoverIntent checks * to see if the user's mouse has slowed down (beneath the sensitivity * threshold) before firing the onMouseOver event. * * hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+ * <http://cherne.net/brian/resources/jquery.hoverIntent.html> * * hoverIntent is currently available for use in all personal or commercial * projects under both MIT and GPL licenses. This means that you can choose * the license that best suits your project, and use it accordingly. * * // basic usage (just like .hover) receives onMouseOver and onMouseOut functions * $("ul li").hoverIntent( showNav , hideNav ); * * // advanced usage receives configuration object only * $("ul li").hoverIntent({ * sensitivity: 7, // number = sensitivity threshold (must be 1 or higher) * interval: 100, // number = milliseconds of polling interval * over: showNav, // function = onMouseOver callback (required) * timeout: 0, // number = milliseconds delay before onMouseOut function call * out: hideNav // function = onMouseOut callback (required) * }); * * @param f onMouseOver function || An object with configuration options * @param g onMouseOut function || Nothing (use configuration options object) * @author Brian Cherne brian(at)cherne(dot)net */ (function($) { $.fn.hoverIntent = function(f,g) { // default configuration options var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; // override configuration options with user supplied object cfg = $.extend(cfg, g ? { over: f, out: g } : f ); // instantiate variables // cX, cY = current X and Y position of mouse, updated by mousemove event // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval var cX, cY, pX, pY; // A private function for getting mouse position var track = function(ev) { cX = ev.pageX; cY = ev.pageY; }; // A private function for comparing current and previous mouse position var compare = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); // compare mouse positions to see if they've crossed the threshold if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { $(ob).unbind("mousemove",track); // set hoverIntent state to true (so mouseOut can be called) ob.hoverIntent_s = 1; return cfg.over.apply(ob,[ev]); } else { // set previous coordinates for next time pX = cX; pY = cY; // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); } }; // A private function for delaying the mouseOut function var delay = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob,[ev]); }; // A private function for handling mouse 'hovering' var handleHover = function(e) { // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); var ob = this; // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // if e.type == "mouseenter" if (e.type == "mouseenter") { // set "previous" X and Y position based on initial entry point pX = ev.pageX; pY = ev.pageY; // update "current" X and Y position based on mousemove $(ob).bind("mousemove",track); // start polling interval (self-calling timeout) to compare mouse coordinates over time if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} // else e.type == "mouseleave" } else { // unbind expensive mousemove event $(ob).unbind("mousemove",track); // if hoverIntent state is true, then call the mouseOut function after the specified delay if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} } }; // bind the function to the two event listeners return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover); }; })(jQuery);
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'http://www.entwurvian.net/wip/maxivision3/backend/js/jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // NOTE Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
// script.aculo.us builder.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ var Builder = { NODEMAP: { AREA: 'map', CAPTION: 'table', COL: 'table', COLGROUP: 'table', LEGEND: 'fieldset', OPTGROUP: 'select', OPTION: 'select', PARAM: 'object', TBODY: 'table', TD: 'table', TFOOT: 'table', TH: 'table', THEAD: 'table', TR: 'table' }, // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, // due to a Firefox bug node: function(elementName) { elementName = elementName.toUpperCase(); // try innerHTML approach var parentTag = this.NODEMAP[elementName] || 'div'; var parentElement = document.createElement(parentTag); try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; } catch(e) {} var element = parentElement.firstChild || null; // see if browser added wrapping tags if(element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0]; // fallback to createElement approach if(!element) element = document.createElement(elementName); // abort if nothing could be created if(!element) return; // attributes (or text) if(arguments[1]) if(this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) { this._children(element, arguments[1]); } else { var attrs = this._attributes(arguments[1]); if(attrs.length) { try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" +elementName + " " + attrs + "></" + elementName + ">"; } catch(e) {} element = parentElement.firstChild || null; // workaround firefox 1.0.X bug if(!element) { element = document.createElement(elementName); for(attr in arguments[1]) element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; } if(element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0]; } } // text, or array of children if(arguments[2]) this._children(element, arguments[2]); return element; }, _text: function(text) { return document.createTextNode(text); }, ATTR_MAP: { 'className': 'class', 'htmlFor': 'for' }, _attributes: function(attributes) { var attrs = []; for(attribute in attributes) attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"'); return attrs.join(" "); }, _children: function(element, children) { if(children.tagName) { element.appendChild(children); return; } if(typeof children=='object') { // array can hold nodes and text children.flatten().each( function(e) { if(typeof e=='object') element.appendChild(e) else if(Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e)); }); } else if(Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children)); }, _isStringOrNumber: function(param) { return(typeof param=='string' || typeof param=='number'); }, build: function(html) { var element = this.node('div'); $(element).update(html.strip()); return element.down(); }, dump: function(scope) { if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/); tags.each( function(tag){ scope[tag] = function() { return Builder.node.apply(Builder, [tag].concat($A(arguments))); } }); } }
JavaScript
//Gradual Elements Fader- By Dynamic Drive at http://www.dynamicdrive.com //Last updated: Nov 8th, 07' var gfader={} gfader.baseopacity=0 //set base opacity when mouse isn't over element (decimal below 1) gfader.increment=0.2 //amount of opacity to increase after each iteration (suggestion: 0.1 or 0.2) document.write('<style type="text/css">\n') //write out CSS to enable opacity on "gfader" class document.write('.gfader{filter:progid:DXImageTransform.Microsoft.alpha(opacity='+gfader.baseopacity*100+'); -moz-opacity:'+gfader.baseopacity+'; opacity:'+gfader.baseopacity+';}\n') document.write('</style>') gfader.setopacity=function(obj, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) var targetobject=obj if (targetobject && targetobject.filters && targetobject.filters[0]){ //IE syntax if (typeof targetobject.filters[0].opacity=="number") //IE6 targetobject.filters[0].opacity=value*100 else //IE 5.5 targetobject.style.filter="alpha(opacity="+value*100+")" } else if (targetobject && typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax targetobject.style.MozOpacity=value else if (targetobject && typeof targetobject.style.opacity!="undefined") //Standard opacity syntax targetobject.style.opacity=value targetobject.currentopacity=value } gfader.fadeupdown=function(obj, direction){ var targetobject=obj var fadeamount=(direction=="fadeup")? this.increment : -this.increment if (targetobject && (direction=="fadeup" && targetobject.currentopacity<1 || direction=="fadedown" && targetobject.currentopacity>this.baseopacity)){ this.setopacity(obj, targetobject.currentopacity+fadeamount) window["opacityfader"+obj._fadeorder]=setTimeout(function(){gfader.fadeupdown(obj, direction)}, 50) } } gfader.clearTimer=function(obj){ if (typeof window["opacityfader"+obj._fadeorder]!="undefined") clearTimeout(window["opacityfader"+obj._fadeorder]) } gfader.isContained=function(m, e){ var e=window.event || e var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement) while (c && c!=m)try {c=c.parentNode} catch(e){c=m} if (c==m) return true else return false } gfader.fadeinterface=function(obj, e, direction){ if (!this.isContained(obj, e)){ gfader.clearTimer(obj) gfader.fadeupdown(obj, direction) } } gfader.collectElementbyClass=function(classname){ //Returns an array containing DIVs with specified classname var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i") //regular expression to screen for classname within element var pieces=[] var alltags=document.all? document.all : document.getElementsByTagName("*") for (var i=0; i<alltags.length; i++){ if (typeof alltags[i].className=="string" && alltags[i].className.search(classnameRE)!=-1) pieces[pieces.length]=alltags[i] } return pieces } gfader.init=function(){ var targetobjects=this.collectElementbyClass("gfader") for (var i=0; i<targetobjects.length; i++){ targetobjects[i]._fadeorder=i this.setopacity(targetobjects[i], this.baseopacity) targetobjects[i].onmouseover=function(e){gfader.fadeinterface(this, e, "fadeup")} targetobjects[i].onmouseout=function(e){gfader.fadeinterface(this, e, "fadedown")} } } /*********************************************** * Cool DHTML tooltip script II- ? Dynamic Drive DHTML code library (www.dynamicdrive.com) ***********************************************/ var offsetfromcursorX=12 //Customize x offset of tooltip var offsetfromcursorY=10 //Customize y offset of tooltip var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1). document.write('<div id="gfitooltip"></div>') //write out tooltip DIV document.write('<img id="gfipointer" src="images/arrow.gif">') //write out pointer image var ie=document.all var ns6=document.getElementById && !document.all var enabletip=false if (ie||ns6) var tipobj=document.all? document.all["gfitooltip"] : document.getElementById? document.getElementById("gfitooltip") : "" var pointerobj=document.all? document.all["gfipointer"] : document.getElementById? document.getElementById("gfipointer") : "" function ietruebody(){ return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body } function tip(thetext, thewidth, thecolor){ if (ns6||ie){ if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px" if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor tipobj.innerHTML=thetext enabletip=true return false } } function positiontip(e){ if (enabletip){ var nondefaultpos=false var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft; var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop; //Find out how close the mouse is to the corner of the window var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20 var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20 var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000 //if the horizontal distance isn't enough to accomodate the width of the context menu if (rightedge<tipobj.offsetWidth){ //move the horizontal position of the menu to the left by it's width tipobj.style.left=curX-tipobj.offsetWidth+"px" nondefaultpos=true } else if (curX<leftedge) tipobj.style.left="5px" else{ //position the horizontal position of the menu where the mouse is positioned tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px" pointerobj.style.left=curX+offsetfromcursorX+"px" } //same concept with the vertical position if (bottomedge<tipobj.offsetHeight){ tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px" nondefaultpos=true } else{ tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px" pointerobj.style.top=curY+offsetfromcursorY+"px" } tipobj.style.visibility="visible" if (!nondefaultpos) pointerobj.style.visibility="visible" else pointerobj.style.visibility="hidden" } } function hidetip(){ if (ns6||ie){ enabletip=false tipobj.style.visibility="hidden" pointerobj.style.visibility="hidden" tipobj.style.left="-1000px" tipobj.style.backgroundColor='' tipobj.style.width='' } } document.onmousemove=positiontip
JavaScript
 /** * @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time at http://ckeditor.com/builder to build CKEditor again. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moono', preset: 'standard', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'about' : 1, 'a11yhelp' : 1, 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'resize' : 1, 'toolbar' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'htmlwriter' : 1, 'horizontalrule' : 1, 'wysiwygarea' : 1, 'image' : 1, 'indent' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastetext' : 1, 'pastefromword' : 1, 'removeformat' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'undo' : 1, 'dialog' : 1, 'dialogui' : 1, 'menu' : 1, 'floatpanel' : 1, 'panel' : 1, 'button' : 1, 'popup' : 1, 'richcombo' : 1, 'listblock' : 1, 'fakeobjects' : 1 }, languages : { 'af' : 1, 'ar' : 1, 'eu' : 1, 'bn' : 1, 'bs' : 1, 'bg' : 1, 'ca' : 1, 'zh-cn' : 1, 'zh' : 1, 'hr' : 1, 'cs' : 1, 'da' : 1, 'nl' : 1, 'en' : 1, 'en-au' : 1, 'en-ca' : 1, 'en-gb' : 1, 'eo' : 1, 'et' : 1, 'fo' : 1, 'fi' : 1, 'fr' : 1, 'fr-ca' : 1, 'gl' : 1, 'ka' : 1, 'de' : 1, 'el' : 1, 'gu' : 1, 'he' : 1, 'hi' : 1, 'hu' : 1, 'is' : 1, 'it' : 1, 'ja' : 1, 'km' : 1, 'ko' : 1, 'ku' : 1, 'lv' : 1, 'lt' : 1, 'mk' : 1, 'ms' : 1, 'mn' : 1, 'no' : 1, 'nb' : 1, 'fa' : 1, 'pl' : 1, 'pt-br' : 1, 'pt' : 1, 'ro' : 1, 'ru' : 1, 'sr' : 1, 'sr-latn' : 1, 'sk' : 1, 'sl' : 1, 'es' : 1, 'sv' : 1, 'th' : 1, 'tr' : 1, 'ug' : 1, 'uk' : 1, 'vi' : 1, 'cy' : 1, } };
JavaScript
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
/** * @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. // For the complete reference: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. config.toolbarGroups = [ { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'links' }, { name: 'insert' }, { name: 'forms' }, { name: 'tools' }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'others' }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ] }, { name: 'styles' }, { name: 'colors',items: ['TextColor', 'BGColor'] } ]; // Remove some buttons, provided by the standard plugins, which we don't // need to have in the Standard(s) toolbar. config.removeButtons = 'Underline,Subscript,Superscript'; };
JavaScript
/** * Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin, which shows a combo // in the editor toolbar, containing all styles. Other plugins instead, like // the div plugin, use a subset of the styles on their feature. // // If you don't have plugins that depend on this file, you can simply ignore it. // Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. CKEDITOR.stylesSet.add( 'default', [ /* Block Styles */ // These styles are already available in the "Format" combo ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline Styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles combo, removing them from the toolbar. // (This requires the "stylescombo" plugin) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } }, { name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object Styles */ { name: 'Styled image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } } ]);
JavaScript
/* SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ ;var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null; if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true; X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10); ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0;}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version"); if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}; }(),k=function(){if(!M.w3){return;}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f(); }if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false);}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee); f();}});if(O==top){(function(){if(J){return;}try{j.documentElement.doScroll("left");}catch(X){setTimeout(arguments.callee,0);return;}f();})();}}if(M.wk){(function(){if(J){return; }if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return;}f();})();}s(f);}}();function f(){if(J){return;}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span")); Z.parentNode.removeChild(Z);}catch(aa){return;}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]();}}function K(X){if(J){X();}else{U[U.length]=X;}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false); }else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false);}else{if(typeof O.attachEvent!=D){i(O,"onload",Y);}else{if(typeof O.onload=="function"){var X=O.onload; O.onload=function(){X();Y();};}else{O.onload=Y;}}}}}function h(){if(T){V();}else{H();}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r); aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(","); M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)];}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return;}}X.removeChild(aa);Z=null;H(); })();}else{H();}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y); if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa);}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall; ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class");}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align"); }var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value"); }}P(ai,ah,Y,ab);}else{p(ae);if(ab){ab(aa);}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z;}ab(aa);}}}}}function z(aa){var X=null; var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y;}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z;}}}return X;}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312); }function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null;}else{l=ae;Q=X;}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"; }if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137";}j.title=j.title.slice(0,47)+" - Flash Player Installation"; var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac; }else{ab.flashvars=ac;}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none"; (function(){if(ae.readyState==4){ae.parentNode.removeChild(ae);}else{setTimeout(arguments.callee,10);}})();}u(aa,ab,X);}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div"); Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y);}else{setTimeout(arguments.callee,10); }})();}else{Y.parentNode.replaceChild(g(Y),Y);}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML;}else{var Y=ab.getElementsByTagName(r)[0]; if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true)); }}}}}return aa;}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X;}if(aa){if(typeof ai.id==D){ai.id=Y;}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]; }else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"';}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"';}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'; }}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id);}else{var Z=C(r);Z.setAttribute("type",q); for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac]);}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac]); }}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab]);}}aa.parentNode.replaceChild(Z,aa);X=Z;}}return X;}function e(Z,X,Y){var aa=C("param"); aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa);}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none"; (function(){if(X.readyState==4){b(Y);}else{setTimeout(arguments.callee,10);}})();}else{X.parentNode.removeChild(X);}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null; }}Y.parentNode.removeChild(Y);}}function c(Z){var X=null;try{X=j.getElementById(Z);}catch(Y){}return X;}function C(X){return j.createElement(X);}function i(Z,X,Y){Z.attachEvent(X,Y); I[I.length]=[Z,X,Y];}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false; }function v(ac,Y,ad,ab){if(M.ie&&M.mac){return;}var aa=j.getElementsByTagName("head")[0];if(!aa){return;}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null; G=null;}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]; }G=X;}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y);}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}")); }}}function w(Z,X){if(!m){return;}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y;}else{v("#"+Z,"visibility:"+Y);}}function L(Y){var Z=/[\\\"<>\.;]/; var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y;}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length; for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2]);}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa]);}for(var Y in M){M[Y]=null;}M=null;for(var X in swfobject){swfobject[X]=null; }swfobject=null;});}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y; w(ab,false);}else{if(Z){Z({success:false,id:ab});}}},getObjectById:function(X){if(M.w3){return z(X);}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah}; if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al];}}aj.data=ab; aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak];}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]; }else{am.flashvars=ai+"="+Z[ai];}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true);}X.success=true;X.ref=an;}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac); return;}else{w(ah,true);}}if(ac){ac(X);}});}else{if(ac){ac(X);}}},switchOffAutoHideShow:function(){m=false;},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}; },hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X);}else{return undefined;}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y); }},removeSWF:function(X){if(M.w3){y(X);}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X);}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash; if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1];}if(aa==null){return L(Z);}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1))); }}}return"";},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"; }}if(E){E(B);}}a=false;}}};}(); /* SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License: http://www.opensource.org/licenses/mit-license.php SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License: http://www.opensource.org/licenses/mit-license.php */ var SWFUpload;if(SWFUpload==undefined){SWFUpload=function(a){this.initSWFUpload(a)}}SWFUpload.prototype.initSWFUpload=function(b){try{this.customSettings={};this.settings=b;this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings();this.loadFlash();this.displayDebugInfo()}catch(a){delete SWFUpload.instances[this.movieName];throw a}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.2.0 2009-03-25";SWFUpload.QUEUE_ERROR={QUEUE_LIMIT_EXCEEDED:-100,FILE_EXCEEDS_SIZE_LIMIT:-110,ZERO_BYTE_FILE:-120,INVALID_FILETYPE:-130};SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.completeURL=function(a){if(typeof(a)!=="string"||a.match(/^https?:\/\//i)||a.match(/^\//)){return a}var c=window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"");var b=window.location.pathname.lastIndexOf("/");if(b<=0){path="/"}else{path=window.location.pathname.substr(0,b)+"/"}return path+a};SWFUpload.prototype.initSettings=function(){this.ensureDefault=function(b,a){this.settings[b]=(this.settings[b]==undefined)?a:this.settings[b]};this.ensureDefault("upload_url","");this.ensureDefault("preserve_relative_urls",false);this.ensureDefault("file_post_name","Filedata");this.ensureDefault("post_params",{});this.ensureDefault("use_query_string",false);this.ensureDefault("requeue_on_error",false);this.ensureDefault("http_success",[]);this.ensureDefault("assume_success_timeout",0);this.ensureDefault("file_types","*.*");this.ensureDefault("file_types_description","All Files");this.ensureDefault("file_size_limit",0);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","swfupload.swf");this.ensureDefault("prevent_swf_caching",true);this.ensureDefault("button_image_url","");this.ensureDefault("button_width",1);this.ensureDefault("button_height",1);this.ensureDefault("button_text","");this.ensureDefault("button_text_style","color: #000000; font-size: 16pt;");this.ensureDefault("button_text_top_padding",0);this.ensureDefault("button_text_left_padding",0);this.ensureDefault("button_action",SWFUpload.BUTTON_ACTION.SELECT_FILES);this.ensureDefault("button_disabled",false);this.ensureDefault("button_placeholder_id","");this.ensureDefault("button_placeholder",null);this.ensureDefault("button_cursor",SWFUpload.CURSOR.ARROW);this.ensureDefault("button_window_mode",SWFUpload.WINDOW_MODE.WINDOW);this.ensureDefault("debug",false);this.settings.debug_enabled=this.settings.debug;this.settings.return_upload_start_handler=this.returnUploadStart;this.ensureDefault("swfupload_loaded_handler",null);this.ensureDefault("file_dialog_start_handler",null);this.ensureDefault("file_queued_handler",null);this.ensureDefault("file_queue_error_handler",null);this.ensureDefault("file_dialog_complete_handler",null);this.ensureDefault("upload_start_handler",null);this.ensureDefault("upload_progress_handler",null);this.ensureDefault("upload_error_handler",null);this.ensureDefault("upload_success_handler",null);this.ensureDefault("upload_complete_handler",null);this.ensureDefault("debug_handler",this.debugMessage);this.ensureDefault("custom_settings",{});this.customSettings=this.settings.custom_settings;if(!!this.settings.prevent_swf_caching){this.settings.flash_url=this.settings.flash_url+(this.settings.flash_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+new Date().getTime()}if(!this.settings.preserve_relative_urls){this.settings.upload_url=SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url=SWFUpload.completeURL(this.settings.button_image_url)}delete this.ensureDefault};SWFUpload.prototype.loadFlash=function(){var a,b;if(document.getElementById(this.movieName)!==null){throw"ID "+this.movieName+" is already in use. The Flash Object could not be added"}a=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(a==undefined){throw"Could not find the placeholder element: "+this.settings.button_placeholder_id}b=document.createElement("div");b.innerHTML=this.getFlashHTML();a.parentNode.replaceChild(b.firstChild,a);if(window[this.movieName]==undefined){window[this.movieName]=this.getMovieElement()}};SWFUpload.prototype.getFlashHTML=function(){return['<object id="',this.movieName,'" type="application/x-shockwave-flash" data="',this.settings.flash_url,'" width="',this.settings.button_width,'" height="',this.settings.button_height,'" class="swfupload">','<param name="wmode" value="',this.settings.button_window_mode,'" />','<param name="movie" value="',this.settings.flash_url,'" />','<param name="quality" value="high" />','<param name="menu" value="false" />','<param name="allowScriptAccess" value="always" />','<param name="flashvars" value="'+this.getFlashVars()+'" />',"</object>"].join("")};SWFUpload.prototype.getFlashVars=function(){var b=this.buildParamString();var a=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&amp;uploadURL=",encodeURIComponent(this.settings.upload_url),"&amp;useQueryString=",encodeURIComponent(this.settings.use_query_string),"&amp;requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&amp;httpSuccess=",encodeURIComponent(a),"&amp;assumeSuccessTimeout=",encodeURIComponent(this.settings.assume_success_timeout),"&amp;params=",encodeURIComponent(b),"&amp;filePostName=",encodeURIComponent(this.settings.file_post_name),"&amp;fileTypes=",encodeURIComponent(this.settings.file_types),"&amp;fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&amp;fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&amp;fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&amp;fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),"&amp;debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&amp;buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&amp;buttonWidth=",encodeURIComponent(this.settings.button_width),"&amp;buttonHeight=",encodeURIComponent(this.settings.button_height),"&amp;buttonText=",encodeURIComponent(this.settings.button_text),"&amp;buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&amp;buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),"&amp;buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&amp;buttonAction=",encodeURIComponent(this.settings.button_action),"&amp;buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&amp;buttonCursor=",encodeURIComponent(this.settings.button_cursor)].join("")};SWFUpload.prototype.getMovieElement=function(){if(this.movieElement==undefined){this.movieElement=document.getElementById(this.movieName)}if(this.movieElement===null){throw"Could not find Flash element"}return this.movieElement};SWFUpload.prototype.buildParamString=function(){var c=this.settings.post_params;var b=[];if(typeof(c)==="object"){for(var a in c){if(c.hasOwnProperty(a)){b.push(encodeURIComponent(a.toString())+"="+encodeURIComponent(c[a].toString()))}}}return b.join("&amp;")};SWFUpload.prototype.destroy=function(){try{this.cancelUpload(null,false);var a=null;a=this.getMovieElement();if(a&&typeof(a.CallFunction)==="unknown"){for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(e){}}try{a.parentNode.removeChild(a)}catch(b){}}window[this.movieName]=null;SWFUpload.instances[this.movieName]=null;delete SWFUpload.instances[this.movieName];this.movieElement=null;this.settings=null;this.customSettings=null;this.eventQueue=null;this.movieName=null;return true}catch(d){return false}};SWFUpload.prototype.displayDebugInfo=function(){this.debug(["---SWFUpload Instance Info---\n","Version: ",SWFUpload.version,"\n","Movie Name: ",this.movieName,"\n","Settings:\n","\t","upload_url: ",this.settings.upload_url,"\n","\t","flash_url: ",this.settings.flash_url,"\n","\t","use_query_string: ",this.settings.use_query_string.toString(),"\n","\t","requeue_on_error: ",this.settings.requeue_on_error.toString(),"\n","\t","http_success: ",this.settings.http_success.join(", "),"\n","\t","assume_success_timeout: ",this.settings.assume_success_timeout,"\n","\t","file_post_name: ",this.settings.file_post_name,"\n","\t","post_params: ",this.settings.post_params.toString(),"\n","\t","file_types: ",this.settings.file_types,"\n","\t","file_types_description: ",this.settings.file_types_description,"\n","\t","file_size_limit: ",this.settings.file_size_limit,"\n","\t","file_upload_limit: ",this.settings.file_upload_limit,"\n","\t","file_queue_limit: ",this.settings.file_queue_limit,"\n","\t","debug: ",this.settings.debug.toString(),"\n","\t","prevent_swf_caching: ",this.settings.prevent_swf_caching.toString(),"\n","\t","button_placeholder_id: ",this.settings.button_placeholder_id.toString(),"\n","\t","button_placeholder: ",(this.settings.button_placeholder?"Set":"Not Set"),"\n","\t","button_image_url: ",this.settings.button_image_url.toString(),"\n","\t","button_width: ",this.settings.button_width.toString(),"\n","\t","button_height: ",this.settings.button_height.toString(),"\n","\t","button_text: ",this.settings.button_text.toString(),"\n","\t","button_text_style: ",this.settings.button_text_style.toString(),"\n","\t","button_text_top_padding: ",this.settings.button_text_top_padding.toString(),"\n","\t","button_text_left_padding: ",this.settings.button_text_left_padding.toString(),"\n","\t","button_action: ",this.settings.button_action.toString(),"\n","\t","button_disabled: ",this.settings.button_disabled.toString(),"\n","\t","custom_settings: ",this.settings.custom_settings.toString(),"\n","Event Handlers:\n","\t","swfupload_loaded_handler assigned: ",(typeof this.settings.swfupload_loaded_handler==="function").toString(),"\n","\t","file_dialog_start_handler assigned: ",(typeof this.settings.file_dialog_start_handler==="function").toString(),"\n","\t","file_queued_handler assigned: ",(typeof this.settings.file_queued_handler==="function").toString(),"\n","\t","file_queue_error_handler assigned: ",(typeof this.settings.file_queue_error_handler==="function").toString(),"\n","\t","upload_start_handler assigned: ",(typeof this.settings.upload_start_handler==="function").toString(),"\n","\t","upload_progress_handler assigned: ",(typeof this.settings.upload_progress_handler==="function").toString(),"\n","\t","upload_error_handler assigned: ",(typeof this.settings.upload_error_handler==="function").toString(),"\n","\t","upload_success_handler assigned: ",(typeof this.settings.upload_success_handler==="function").toString(),"\n","\t","upload_complete_handler assigned: ",(typeof this.settings.upload_complete_handler==="function").toString(),"\n","\t","debug_handler assigned: ",(typeof this.settings.debug_handler==="function").toString(),"\n"].join(""))};SWFUpload.prototype.addSetting=function(b,c,a){if(c==undefined){return(this.settings[b]=a)}else{return(this.settings[b]=c)}};SWFUpload.prototype.getSetting=function(a){if(this.settings[a]!=undefined){return this.settings[a]}return""};SWFUpload.prototype.callFlash=function(functionName,argumentArray){argumentArray=argumentArray||[];var movieElement=this.getMovieElement();var returnValue,returnString;try{returnString=movieElement.CallFunction('<invoke name="'+functionName+'" returntype="javascript">'+__flash__argumentsToXML(argumentArray,0)+"</invoke>");returnValue=eval(returnString)}catch(ex){throw"Call to "+functionName+" failed"}if(returnValue!=undefined&&typeof returnValue.post==="object"){returnValue=this.unescapeFilePostParams(returnValue)}return returnValue};SWFUpload.prototype.selectFile=function(){this.callFlash("SelectFile")};SWFUpload.prototype.selectFiles=function(){this.callFlash("SelectFiles")};SWFUpload.prototype.startUpload=function(a){this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelUpload=function(a,b){if(b!==false){b=true}this.callFlash("CancelUpload",[a,b])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(a){this.callFlash("SetStats",[a])};SWFUpload.prototype.getFile=function(a){if(typeof(a)==="number"){return this.callFlash("GetFileByIndex",[a])}else{return this.callFlash("GetFile",[a])}};SWFUpload.prototype.addFileParam=function(a,b,c){return this.callFlash("AddFileParam",[a,b,c])};SWFUpload.prototype.removeFileParam=function(a,b){this.callFlash("RemoveFileParam",[a,b])};SWFUpload.prototype.setUploadURL=function(a){this.settings.upload_url=a.toString();this.callFlash("SetUploadURL",[a])};SWFUpload.prototype.setPostParams=function(a){this.settings.post_params=a;this.callFlash("SetPostParams",[a])};SWFUpload.prototype.addPostParam=function(a,b){this.settings.post_params[a]=b;this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.removePostParam=function(a){delete this.settings.post_params[a];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(a,b){this.settings.file_types=a;this.settings.file_types_description=b;this.callFlash("SetFileTypes",[a,b])};SWFUpload.prototype.setFileSizeLimit=function(a){this.settings.file_size_limit=a;this.callFlash("SetFileSizeLimit",[a])};SWFUpload.prototype.setFileUploadLimit=function(a){this.settings.file_upload_limit=a;this.callFlash("SetFileUploadLimit",[a])};SWFUpload.prototype.setFileQueueLimit=function(a){this.settings.file_queue_limit=a;this.callFlash("SetFileQueueLimit",[a])};SWFUpload.prototype.setFilePostName=function(a){this.settings.file_post_name=a;this.callFlash("SetFilePostName",[a])};SWFUpload.prototype.setUseQueryString=function(a){this.settings.use_query_string=a;this.callFlash("SetUseQueryString",[a])};SWFUpload.prototype.setRequeueOnError=function(a){this.settings.requeue_on_error=a;this.callFlash("SetRequeueOnError",[a])};SWFUpload.prototype.setHTTPSuccess=function(a){if(typeof a==="string"){a=a.replace(" ","").split(",")}this.settings.http_success=a;this.callFlash("SetHTTPSuccess",[a])};SWFUpload.prototype.setAssumeSuccessTimeout=function(a){this.settings.assume_success_timeout=a;this.callFlash("SetAssumeSuccessTimeout",[a])};SWFUpload.prototype.setDebugEnabled=function(a){this.settings.debug_enabled=a;this.callFlash("SetDebugEnabled",[a])};SWFUpload.prototype.setButtonImageURL=function(a){if(a==undefined){a=""}this.settings.button_image_url=a;this.callFlash("SetButtonImageURL",[a])};SWFUpload.prototype.setButtonDimensions=function(c,a){this.settings.button_width=c;this.settings.button_height=a;var b=this.getMovieElement();if(b!=undefined){b.style.width=c+"px";b.style.height=a+"px"}this.callFlash("SetButtonDimensions",[c,a])};SWFUpload.prototype.setButtonText=function(a){this.settings.button_text=a;this.callFlash("SetButtonText",[a])};SWFUpload.prototype.setButtonTextPadding=function(b,a){this.settings.button_text_top_padding=a;this.settings.button_text_left_padding=b;this.callFlash("SetButtonTextPadding",[b,a])};SWFUpload.prototype.setButtonTextStyle=function(a){this.settings.button_text_style=a;this.callFlash("SetButtonTextStyle",[a])};SWFUpload.prototype.setButtonDisabled=function(a){this.settings.button_disabled=a;this.callFlash("SetButtonDisabled",[a])};SWFUpload.prototype.setButtonAction=function(a){this.settings.button_action=a;this.callFlash("SetButtonAction",[a])};SWFUpload.prototype.setButtonCursor=function(a){this.settings.button_cursor=a;this.callFlash("SetButtonCursor",[a])};SWFUpload.prototype.queueEvent=function(b,c){if(c==undefined){c=[]}else{if(!(c instanceof Array)){c=[c]}}var a=this;if(typeof this.settings[b]==="function"){this.eventQueue.push(function(){this.settings[b].apply(this,c)});setTimeout(function(){a.executeNextEvent()},0)}else{if(this.settings[b]!==null){throw"Event handler "+b+" is unknown or is not a function"}}};SWFUpload.prototype.executeNextEvent=function(){var a=this.eventQueue?this.eventQueue.shift():null;if(typeof(a)==="function"){a.apply(this)}};SWFUpload.prototype.unescapeFilePostParams=function(c){var e=/[$]([0-9a-f]{4})/i;var f={};var d;if(c!=undefined){for(var a in c.post){if(c.post.hasOwnProperty(a)){d=a;var b;while((b=e.exec(d))!==null){d=d.replace(b[0],String.fromCharCode(parseInt("0x"+b[1],16)))}f[d]=c.post[a]}}c.post=f}return c};SWFUpload.prototype.testExternalInterface=function(){try{return this.callFlash("TestExternalInterface")}catch(a){return false}};SWFUpload.prototype.flashReady=function(){var a=this.getMovieElement();if(!a){this.debug("Flash called back ready but the flash movie can't be found.");return}this.cleanUp(a);this.queueEvent("swfupload_loaded_handler")};SWFUpload.prototype.cleanUp=function(a){try{if(this.movieElement&&typeof(a.CallFunction)==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(var c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(b){}}}}catch(d){}window.__flash__removeCallback=function(e,f){try{if(e){e[f]=null}}catch(g){}}};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("file_queued_handler",a)};SWFUpload.prototype.fileQueueError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("file_queue_error_handler",[a,c,b])};SWFUpload.prototype.fileDialogComplete=function(b,c,a){this.queueEvent("file_dialog_complete_handler",[b,c,a])};SWFUpload.prototype.uploadStart=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("return_upload_start_handler",a)};SWFUpload.prototype.returnUploadStart=function(a){var b;if(typeof this.settings.upload_start_handler==="function"){a=this.unescapeFilePostParams(a);b=this.settings.upload_start_handler.call(this,a)}else{if(this.settings.upload_start_handler!=undefined){throw"upload_start_handler must be a function"}}if(b===undefined){b=true}b=!!b;this.callFlash("ReturnUploadStart",[b])};SWFUpload.prototype.uploadProgress=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_progress_handler",[a,c,b])};SWFUpload.prototype.uploadError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_error_handler",[a,c,b])};SWFUpload.prototype.uploadSuccess=function(b,a,c){b=this.unescapeFilePostParams(b);this.queueEvent("upload_success_handler",[b,a,c])};SWFUpload.prototype.uploadComplete=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("upload_complete_handler",a)};SWFUpload.prototype.debug=function(a){this.queueEvent("debug_handler",a)};SWFUpload.prototype.debugMessage=function(c){if(this.settings.debug){var a,d=[];if(typeof c==="object"&&typeof c.name==="string"&&typeof c.message==="string"){for(var b in c){if(c.hasOwnProperty(b)){d.push(b+": "+c[b])}}a=d.join("\n")||"";d=a.split("\n");a="EXCEPTION: "+d.join("\nEXCEPTION: ");SWFUpload.Console.writeLine(a)}else{SWFUpload.Console.writeLine(c)}}};SWFUpload.Console={};SWFUpload.Console.writeLine=function(d){var b,a;try{b=document.getElementById("SWFUpload_Console");if(!b){a=document.createElement("form");document.getElementsByTagName("body")[0].appendChild(a);b=document.createElement("textarea");b.id="SWFUpload_Console";b.style.fontFamily="monospace";b.setAttribute("wrap","off");b.wrap="off";b.style.overflow="auto";b.style.width="700px";b.style.height="350px";b.style.margin="5px";a.appendChild(b)}b.value+=d+"\n";b.scrollTop=b.scrollHeight-b.clientHeight}catch(c){alert("Exception: "+c.name+" Message: "+c.message)}}; /* Uploadify v3.2 Copyright (c) 2012 Reactive Apps, Ronnie Garcia Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ (function($) { // These methods can be called by adding them as the first argument in the uploadify plugin call var methods = { init : function(options, swfUploadOptions) { return this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this); // Clone the original DOM object var $clone = $this.clone(); // Setup the default options var settings = $.extend({ // Required Settings id : $this.attr('id'), // The ID of the DOM object swf : 'uploadify.swf', // The path to the uploadify SWF file uploader : 'uploadify.php', // The path to the server-side upload script // Options auto : true, // Automatically upload files when added to the queue buttonClass : '', // A class name to add to the browse button DOM object buttonCursor : 'hand', // The cursor to use with the browse button buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button buttonText : 'SELECT FILES', // The text to use for the browse button checkExisting : false, // The path to a server-side script that checks for existing files on the server debug : false, // Turn on swfUpload debugging mode fileObjName : 'Filedata', // The name of the file object to use in your server-side script fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit) fileTypeDesc : 'All Files', // The description for file types in the browse dialog fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used) height : 30, // The height of the browse button itemTemplate : false, // The template for the file item in the queue method : 'post', // The method to use when sending files to the server-side upload script multi : true, // Allow multiple file selection in the browse dialog formData : {}, // An object with additional data to send to the server-side upload script with every file upload preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters) progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload queueID : false, // The ID of the DOM object to use as a file queue (without the #) queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time removeCompleted : true, // Remove queue items from the queue when they are done uploading removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true requeueErrors : false, // Keep errored files in the queue and keep trying to upload them successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading uploadLimit : 0, // The maximum number of files you can upload width : 120, // The width of the browse button // Events overrideEvents : [] // (Array) A list of default event handlers to skip /* onCancel // Triggered when a file is cancelled from the queue onClearQueue // Triggered during the 'clear queue' method onDestroy // Triggered when the uploadify object is destroyed onDialogClose // Triggered when the browse dialog is closed onDialogOpen // Triggered when the browse dialog is opened onDisable // Triggered when the browse button gets disabled onEnable // Triggered when the browse button gets enabled onFallback // Triggered is Flash is not detected onInit // Triggered when Uploadify is initialized onQueueComplete // Triggered when all files in the queue have been uploaded onSelectError // Triggered when an error occurs while selecting a file (file size, queue size limit, etc.) onSelect // Triggered for each file that is selected onSWFReady // Triggered when the SWF button is loaded onUploadComplete // Triggered when a file upload completes (success or error) onUploadError // Triggered when a file upload returns an error onUploadSuccess // Triggered when a file is uploaded successfully onUploadProgress // Triggered every time a file progress is updated onUploadStart // Triggered immediately before a file upload starts */ }, options); // Prepare settings for SWFUpload var swfUploadSettings = { assume_success_timeout : settings.successTimeout, button_placeholder_id : settings.id, button_width : settings.width, button_height : settings.height, button_text : null, button_text_style : null, button_text_top_padding : 0, button_text_left_padding : 0, button_action : (settings.multi ? SWFUpload.BUTTON_ACTION.SELECT_FILES : SWFUpload.BUTTON_ACTION.SELECT_FILE), button_disabled : false, button_cursor : (settings.buttonCursor == 'arrow' ? SWFUpload.CURSOR.ARROW : SWFUpload.CURSOR.HAND), button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT, debug : settings.debug, requeue_on_error : settings.requeueErrors, file_post_name : settings.fileObjName, file_size_limit : settings.fileSizeLimit, file_types : settings.fileTypeExts, file_types_description : settings.fileTypeDesc, file_queue_limit : settings.queueSizeLimit, file_upload_limit : settings.uploadLimit, flash_url : settings.swf, prevent_swf_caching : settings.preventCaching, post_params : settings.formData, upload_url : settings.uploader, use_query_string : (settings.method == 'get'), // Event Handlers file_dialog_complete_handler : handlers.onDialogClose, file_dialog_start_handler : handlers.onDialogOpen, file_queued_handler : handlers.onSelect, file_queue_error_handler : handlers.onSelectError, swfupload_loaded_handler : settings.onSWFReady, upload_complete_handler : handlers.onUploadComplete, upload_error_handler : handlers.onUploadError, upload_progress_handler : handlers.onUploadProgress, upload_start_handler : handlers.onUploadStart, upload_success_handler : handlers.onUploadSuccess } // Merge the user-defined options with the defaults if (swfUploadOptions) { swfUploadSettings = $.extend(swfUploadSettings, swfUploadOptions); } // Add the user-defined settings to the swfupload object swfUploadSettings = $.extend(swfUploadSettings, settings); // Detect if Flash is available var playerVersion = swfobject.getFlashPlayerVersion(); var flashInstalled = (playerVersion.major >= 9); if (flashInstalled) { // Create the swfUpload instance window['uploadify_' + settings.id] = new SWFUpload(swfUploadSettings); var swfuploadify = window['uploadify_' + settings.id]; // Add the SWFUpload object to the elements data object $this.data('uploadify', swfuploadify); // Wrap the instance var $wrapper = $('<div />', { 'id' : settings.id, 'class' : 'uploadify', 'css' : { 'height' : settings.height + 'px', 'width' : settings.width + 'px' } }); $('#' + swfuploadify.movieName).wrap($wrapper); // Recreate the reference to wrapper $wrapper = $('#' + settings.id); // Add the data object to the wrapper $wrapper.data('uploadify', swfuploadify); // Create the button var $button = $('<div />', { 'id' : settings.id + '-button', 'class' : 'uploadify-button ' + settings.buttonClass }); if (settings.buttonImage) { $button.css({ 'background-image' : "url('" + settings.buttonImage + "')", 'text-indent' : '-9999px' }); } $button.html('<span class="uploadify-button-text">' + settings.buttonText + '</span>') .css({ 'height' : settings.height + 'px', 'line-height' : settings.height + 'px', 'width' : settings.width + 'px' }); // Append the button to the wrapper $wrapper.append($button); // Adjust the styles of the movie $('#' + swfuploadify.movieName).css({ 'position' : 'absolute', 'z-index' : 1 }); // Create the file queue if (!settings.queueID) { var $queue = $('<div />', { 'id' : settings.id + '-queue', 'class' : 'uploadify-queue' }); $wrapper.after($queue); swfuploadify.settings.queueID = settings.id + '-queue'; swfuploadify.settings.defaultQueue = true; } // Create some queue related objects and variables swfuploadify.queueData = { files : {}, // The files in the queue filesSelected : 0, // The number of files selected in the last select operation filesQueued : 0, // The number of files added to the queue in the last select operation filesReplaced : 0, // The number of files replaced in the last select operation filesCancelled : 0, // The number of files that were cancelled instead of replaced filesErrored : 0, // The number of files that caused error in the last select operation uploadsSuccessful : 0, // The number of files that were successfully uploaded uploadsErrored : 0, // The number of files that returned errors during upload averageSpeed : 0, // The average speed of the uploads in KB queueLength : 0, // The number of files in the queue queueSize : 0, // The size in bytes of the entire queue uploadSize : 0, // The size in bytes of the upload queue queueBytesUploaded : 0, // The size in bytes that have been uploaded for the current upload queue uploadQueue : [], // The files currently to be uploaded errorMsg : 'Some files were not added to the queue:' }; // Save references to all the objects swfuploadify.original = $clone; swfuploadify.wrapper = $wrapper; swfuploadify.button = $button; swfuploadify.queue = $queue; // Call the user-defined init event handler if (settings.onInit) settings.onInit.call($this, swfuploadify); } else { // Call the fallback function if (settings.onFallback) settings.onFallback.call($this); } }); }, // Stop a file upload and remove it from the queue cancel : function(fileID, supressEvent) { var args = arguments; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings, delay = -1; if (args[0]) { // Clear the queue if (args[0] == '*') { var queueItemCount = swfuploadify.queueData.queueLength; $('#' + settings.queueID).find('.uploadify-queue-item').each(function() { delay++; if (args[1] === true) { swfuploadify.cancelUpload($(this).attr('id'), false); } else { swfuploadify.cancelUpload($(this).attr('id')); } $(this).find('.data').removeClass('data').html(' - Cancelled'); $(this).find('.uploadify-progress-bar').remove(); $(this).delay(1000 + 100 * delay).fadeOut(500, function() { $(this).remove(); }); }); swfuploadify.queueData.queueSize = 0; swfuploadify.queueData.queueLength = 0; // Trigger the onClearQueue event if (settings.onClearQueue) settings.onClearQueue.call($this, queueItemCount); } else { for (var n = 0; n < args.length; n++) { swfuploadify.cancelUpload(args[n]); $('#' + args[n]).find('.data').removeClass('data').html(' - Cancelled'); $('#' + args[n]).find('.uploadify-progress-bar').remove(); $('#' + args[n]).delay(1000 + 100 * n).fadeOut(500, function() { $(this).remove(); }); } } } else { var item = $('#' + settings.queueID).find('.uploadify-queue-item').get(0); $item = $(item); swfuploadify.cancelUpload($item.attr('id')); $item.find('.data').removeClass('data').html(' - Cancelled'); $item.find('.uploadify-progress-bar').remove(); $item.delay(1000).fadeOut(500, function() { $(this).remove(); }); } }); }, // Revert the DOM object back to its original state destroy : function() { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; // Destroy the SWF object and swfuploadify.destroy(); // Destroy the queue if (settings.defaultQueue) { $('#' + settings.queueID).remove(); } // Reload the original DOM element $('#' + settings.id).replaceWith(swfuploadify.original); // Call the user-defined event handler if (settings.onDestroy) settings.onDestroy.call(this); delete swfuploadify; }); }, // Disable the select button disable : function(isDisabled) { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; // Call the user-defined event handlers if (isDisabled) { swfuploadify.button.addClass('disabled'); if (settings.onDisable) settings.onDisable.call(this); } else { swfuploadify.button.removeClass('disabled'); if (settings.onEnable) settings.onEnable.call(this); } // Enable/disable the browse button swfuploadify.setButtonDisabled(isDisabled); }); }, // Get or set the settings data settings : function(name, value, resetObjects) { var args = arguments; var returnValue = value; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'), settings = swfuploadify.settings; if (typeof(args[0]) == 'object') { for (var n in value) { setData(n,value[n]); } } if (args.length === 1) { returnValue = settings[name]; } else { switch (name) { case 'uploader': swfuploadify.setUploadURL(value); break; case 'formData': if (!resetObjects) { value = $.extend(settings.formData, value); } swfuploadify.setPostParams(settings.formData); break; case 'method': if (value == 'get') { swfuploadify.setUseQueryString(true); } else { swfuploadify.setUseQueryString(false); } break; case 'fileObjName': swfuploadify.setFilePostName(value); break; case 'fileTypeExts': swfuploadify.setFileTypes(value, settings.fileTypeDesc); break; case 'fileTypeDesc': swfuploadify.setFileTypes(settings.fileTypeExts, value); break; case 'fileSizeLimit': swfuploadify.setFileSizeLimit(value); break; case 'uploadLimit': swfuploadify.setFileUploadLimit(value); break; case 'queueSizeLimit': swfuploadify.setFileQueueLimit(value); break; case 'buttonImage': swfuploadify.button.css('background-image', settingValue); break; case 'buttonCursor': if (value == 'arrow') { swfuploadify.setButtonCursor(SWFUpload.CURSOR.ARROW); } else { swfuploadify.setButtonCursor(SWFUpload.CURSOR.HAND); } break; case 'buttonText': $('#' + settings.id + '-button').find('.uploadify-button-text').html(value); break; case 'width': swfuploadify.setButtonDimensions(value, settings.height); break; case 'height': swfuploadify.setButtonDimensions(settings.width, value); break; case 'multi': if (value) { swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILES); } else { swfuploadify.setButtonAction(SWFUpload.BUTTON_ACTION.SELECT_FILE); } break; } settings[name] = value; } }); if (args.length === 1) { return returnValue; } }, // Stop the current uploads and requeue what is in progress stop : function() { this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'); // Reset the queue information swfuploadify.queueData.averageSpeed = 0; swfuploadify.queueData.uploadSize = 0; swfuploadify.queueData.bytesUploaded = 0; swfuploadify.queueData.uploadQueue = []; swfuploadify.stopUpload(); }); }, // Start uploading files in the queue upload : function() { var args = arguments; this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this), swfuploadify = $this.data('uploadify'); // Reset the queue information swfuploadify.queueData.averageSpeed = 0; swfuploadify.queueData.uploadSize = 0; swfuploadify.queueData.bytesUploaded = 0; swfuploadify.queueData.uploadQueue = []; // Upload the files if (args[0]) { if (args[0] == '*') { swfuploadify.queueData.uploadSize = swfuploadify.queueData.queueSize; swfuploadify.queueData.uploadQueue.push('*'); swfuploadify.startUpload(); } else { for (var n = 0; n < args.length; n++) { swfuploadify.queueData.uploadSize += swfuploadify.queueData.files[args[n]].size; swfuploadify.queueData.uploadQueue.push(args[n]); } swfuploadify.startUpload(swfuploadify.queueData.uploadQueue.shift()); } } else { swfuploadify.startUpload(); } }); } } // These functions handle all the events that occur with the file uploader var handlers = { // Triggered when the file dialog is opened onDialogOpen : function() { // Load the swfupload settings var settings = this.settings; // Reset some queue info this.queueData.errorMsg = 'Some files were not added to the queue:'; this.queueData.filesReplaced = 0; this.queueData.filesCancelled = 0; // Call the user-defined event handler if (settings.onDialogOpen) settings.onDialogOpen.call(this); }, // Triggered when the browse dialog is closed onDialogClose : function(filesSelected, filesQueued, queueLength) { // Load the swfupload settings var settings = this.settings; // Update the queue information this.queueData.filesErrored = filesSelected - filesQueued; this.queueData.filesSelected = filesSelected; this.queueData.filesQueued = filesQueued - this.queueData.filesCancelled; this.queueData.queueLength = queueLength; // Run the default event handler if ($.inArray('onDialogClose', settings.overrideEvents) < 0) { if (this.queueData.filesErrored > 0) { alert(this.queueData.errorMsg); } } // Call the user-defined event handler if (settings.onDialogClose) settings.onDialogClose.call(this, this.queueData); // Upload the files if auto is true if (settings.auto) $('#' + settings.id).uploadify('upload', '*'); }, // Triggered once for each file added to the queue onSelect : function(file) { // Load the swfupload settings var settings = this.settings; // Check if a file with the same name exists in the queue var queuedFile = {}; for (var n in this.queueData.files) { queuedFile = this.queueData.files[n]; if (queuedFile.uploaded != true && queuedFile.name == file.name) { var replaceQueueItem = confirm('The file named "' + file.name + '" is already in the queue.\nDo you want to replace the existing item in the queue?'); if (!replaceQueueItem) { this.cancelUpload(file.id); this.queueData.filesCancelled++; return false; } else { $('#' + queuedFile.id).remove(); this.cancelUpload(queuedFile.id); this.queueData.filesReplaced++; } } } // Get the size of the file var fileSize = Math.round(file.size / 1024); var suffix = 'KB'; if (fileSize > 1000) { fileSize = Math.round(fileSize / 1000); suffix = 'MB'; } var fileSizeParts = fileSize.toString().split('.'); fileSize = fileSizeParts[0]; if (fileSizeParts.length > 1) { fileSize += '.' + fileSizeParts[1].substr(0,2); } fileSize += suffix; // Truncate the filename if it's too long var fileName = file.name; if (fileName.length > 25) { fileName = fileName.substr(0,25) + '...'; } // Create the file data object itemData = { 'fileID' : file.id, 'instanceID' : settings.id, 'fileName' : fileName, 'fileSize' : fileSize } // Create the file item template if (settings.itemTemplate == false) { settings.itemTemplate = '<div id="${fileID}" class="uploadify-queue-item">\ <div class="cancel">\ <a href="javascript:$(\'#${instanceID}\').uploadify(\'cancel\', \'${fileID}\')">X</a>\ </div>\ <span class="fileName">${fileName} (${fileSize})</span><span class="data"></span>\ <div class="uploadify-progress">\ <div class="uploadify-progress-bar"><!--Progress Bar--></div>\ </div>\ </div>'; } // Run the default event handler if ($.inArray('onSelect', settings.overrideEvents) < 0) { // Replace the item data in the template itemHTML = settings.itemTemplate; for (var d in itemData) { itemHTML = itemHTML.replace(new RegExp('\\$\\{' + d + '\\}', 'g'), itemData[d]); } // Add the file item to the queue $('#' + settings.queueID).append(itemHTML); } this.queueData.queueSize += file.size; this.queueData.files[file.id] = file; // Call the user-defined event handler if (settings.onSelect) settings.onSelect.apply(this, arguments); }, // Triggered when a file is not added to the queue onSelectError : function(file, errorCode, errorMsg) { // Load the swfupload settings var settings = this.settings; // Run the default event handler if ($.inArray('onSelectError', settings.overrideEvents) < 0) { switch(errorCode) { case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: if (settings.queueSizeLimit > errorMsg) { this.queueData.errorMsg += '\nThe number of files selected exceeds the remaining upload limit (' + errorMsg + ').'; } else { this.queueData.errorMsg += '\nThe number of files selected exceeds the queue size limit (' + settings.queueSizeLimit + ').'; } break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: this.queueData.errorMsg += '\nThe file "' + file.name + '" exceeds the size limit (' + settings.fileSizeLimit + ').'; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: this.queueData.errorMsg += '\nThe file "' + file.name + '" is empty.'; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: this.queueData.errorMsg += '\nThe file "' + file.name + '" is not an accepted file type (' + settings.fileTypeDesc + ').'; break; } } if (errorCode != SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) { delete this.queueData.files[file.id]; } // Call the user-defined event handler if (settings.onSelectError) settings.onSelectError.apply(this, arguments); }, // Triggered when all the files in the queue have been processed onQueueComplete : function() { if (this.settings.onQueueComplete) this.settings.onQueueComplete.call(this, this.settings.queueData); }, // Triggered when a file upload successfully completes onUploadComplete : function(file) { // Load the swfupload settings var settings = this.settings, swfuploadify = this; // Check if all the files have completed uploading var stats = this.getStats(); this.queueData.queueLength = stats.files_queued; if (this.queueData.uploadQueue[0] == '*') { if (this.queueData.queueLength > 0) { this.startUpload(); } else { this.queueData.uploadQueue = []; // Call the user-defined event handler for queue complete if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData); } } else { if (this.queueData.uploadQueue.length > 0) { this.startUpload(this.queueData.uploadQueue.shift()); } else { this.queueData.uploadQueue = []; // Call the user-defined event handler for queue complete if (settings.onQueueComplete) settings.onQueueComplete.call(this, this.queueData); } } // Call the default event handler if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) { if (settings.removeCompleted) { switch (file.filestatus) { case SWFUpload.FILE_STATUS.COMPLETE: setTimeout(function() { if ($('#' + file.id)) { swfuploadify.queueData.queueSize -= file.size; swfuploadify.queueData.queueLength -= 1; delete swfuploadify.queueData.files[file.id] $('#' + file.id).fadeOut(500, function() { $(this).remove(); }); } }, settings.removeTimeout * 1000); break; case SWFUpload.FILE_STATUS.ERROR: if (!settings.requeueErrors) { setTimeout(function() { if ($('#' + file.id)) { swfuploadify.queueData.queueSize -= file.size; swfuploadify.queueData.queueLength -= 1; delete swfuploadify.queueData.files[file.id]; $('#' + file.id).fadeOut(500, function() { $(this).remove(); }); } }, settings.removeTimeout * 1000); } break; } } else { file.uploaded = true; } } // Call the user-defined event handler if (settings.onUploadComplete) settings.onUploadComplete.call(this, file); }, // Triggered when a file upload returns an error onUploadError : function(file, errorCode, errorMsg) { // Load the swfupload settings var settings = this.settings; // Set the error string var errorString = 'Error'; switch(errorCode) { case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: errorString = 'HTTP Error (' + errorMsg + ')'; break; case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: errorString = 'Missing Upload URL'; break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: errorString = 'IO Error'; break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: errorString = 'Security Error'; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: alert('The upload limit has been reached (' + errorMsg + ').'); errorString = 'Exceeds Upload Limit'; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: errorString = 'Failed'; break; case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND: break; case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: errorString = 'Validation Error'; break; case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: errorString = 'Cancelled'; this.queueData.queueSize -= file.size; this.queueData.queueLength -= 1; if (file.status == SWFUpload.FILE_STATUS.IN_PROGRESS || $.inArray(file.id, this.queueData.uploadQueue) >= 0) { this.queueData.uploadSize -= file.size; } // Trigger the onCancel event if (settings.onCancel) settings.onCancel.call(this, file); delete this.queueData.files[file.id]; break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: errorString = 'Stopped'; break; } // Call the default event handler if ($.inArray('onUploadError', settings.overrideEvents) < 0) { if (errorCode != SWFUpload.UPLOAD_ERROR.FILE_CANCELLED && errorCode != SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) { $('#' + file.id).addClass('uploadify-error'); } // Reset the progress bar $('#' + file.id).find('.uploadify-progress-bar').css('width','1px'); // Add the error message to the queue item if (errorCode != SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND && file.status != SWFUpload.FILE_STATUS.COMPLETE) { $('#' + file.id).find('.data').html(' - ' + errorString); } } var stats = this.getStats(); this.queueData.uploadsErrored = stats.upload_errors; // Call the user-defined event handler if (settings.onUploadError) settings.onUploadError.call(this, file, errorCode, errorMsg, errorString); }, // Triggered periodically during a file upload onUploadProgress : function(file, fileBytesLoaded, fileTotalBytes) { // Load the swfupload settings var settings = this.settings; // Setup all the variables var timer = new Date(); var newTime = timer.getTime(); var lapsedTime = newTime - this.timer; if (lapsedTime > 500) { this.timer = newTime; } var lapsedBytes = fileBytesLoaded - this.bytesLoaded; this.bytesLoaded = fileBytesLoaded; var queueBytesLoaded = this.queueData.queueBytesUploaded + fileBytesLoaded; var percentage = Math.round(fileBytesLoaded / fileTotalBytes * 100); // Calculate the average speed var suffix = 'KB/s'; var mbs = 0; var kbs = (lapsedBytes / 1024) / (lapsedTime / 1000); kbs = Math.floor(kbs * 10) / 10; if (this.queueData.averageSpeed > 0) { this.queueData.averageSpeed = Math.floor((this.queueData.averageSpeed + kbs) / 2); } else { this.queueData.averageSpeed = Math.floor(kbs); } if (kbs > 1000) { mbs = (kbs * .001); this.queueData.averageSpeed = Math.floor(mbs); suffix = 'MB/s'; } // Call the default event handler if ($.inArray('onUploadProgress', settings.overrideEvents) < 0) { if (settings.progressData == 'percentage') { $('#' + file.id).find('.data').html(' - ' + percentage + '%'); } else if (settings.progressData == 'speed' && lapsedTime > 500) { $('#' + file.id).find('.data').html(' - ' + this.queueData.averageSpeed + suffix); } $('#' + file.id).find('.uploadify-progress-bar').css('width', percentage + '%'); } // Call the user-defined event handler if (settings.onUploadProgress) settings.onUploadProgress.call(this, file, fileBytesLoaded, fileTotalBytes, queueBytesLoaded, this.queueData.uploadSize); }, // Triggered right before a file is uploaded onUploadStart : function(file) { // Load the swfupload settings var settings = this.settings; var timer = new Date(); this.timer = timer.getTime(); this.bytesLoaded = 0; if (this.queueData.uploadQueue.length == 0) { this.queueData.uploadSize = file.size; } if (settings.checkExisting) { $.ajax({ type : 'POST', async : false, url : settings.checkExisting, data : {filename: file.name}, success : function(data) { if (data == 1) { var overwrite = confirm('A file with the name "' + file.name + '" already exists on the server.\nWould you like to replace the existing file?'); if (!overwrite) { this.cancelUpload(file.id); $('#' + file.id).remove(); if (this.queueData.uploadQueue.length > 0 && this.queueData.queueLength > 0) { if (this.queueData.uploadQueue[0] == '*') { this.startUpload(); } else { this.startUpload(this.queueData.uploadQueue.shift()); } } } } } }); } // Call the user-defined event handler if (settings.onUploadStart) settings.onUploadStart.call(this, file); }, // Triggered when a file upload returns a successful code onUploadSuccess : function(file, data, response) { // Load the swfupload settings var settings = this.settings; var stats = this.getStats(); this.queueData.uploadsSuccessful = stats.successful_uploads; this.queueData.queueBytesUploaded += file.size; // Call the default event handler if ($.inArray('onUploadSuccess', settings.overrideEvents) < 0) { $('#' + file.id).find('.data').html(' - Complete'); } // Call the user-defined event handler if (settings.onUploadSuccess) settings.onUploadSuccess.call(this, file, data, response); } } $.fn.uploadify = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('The method ' + method + ' does not exist in $.uploadify'); } } })($);
JavaScript
/* * jQuery selectbox plugin * * Copyright (c) 2007 Sadri Sahraoui (brainfault.com) * Licensed under the GPL license and MIT: * http://www.opensource.org/licenses/GPL-license.php * http://www.opensource.org/licenses/mit-license.php * * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete) * * Revision: $Id$ * Version: 0.5 * * Changelog : * Version 0.5 * - separate css style for current selected element and hover element which solve the highlight issue * Version 0.4 * - Fix width when the select is in a hidden div @Pawel Maziarz * - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz */ jQuery.fn.extend({ selectbox: function(options) { return this.each(function() { new jQuery.SelectBox(this, options); }); } }); /* pawel maziarz: work around for ie logging */ if (!window.console) { var console = { log: function(msg) { } } } /* */ jQuery.SelectBox = function(selectobj, options) { var opt = options || {}; opt.inputClass = opt.inputClass || "selectbox2"; opt.containerClass = opt.containerClass || "selectbox-wrapper2"; opt.hoverClass = opt.hoverClass || "current2"; opt.currentClass = opt.selectedClass || "selected2" opt.debug = opt.debug || false; var elm_id = selectobj.id; var active = -1; var inFocus = false; var hasfocus = 0; //jquery object for select element var $select = $(selectobj); // jquery container object var $container = setupContainer(opt); //jquery input object var $input = setupInput(opt); // hide select and append newly created elements $select.hide().before($input).before($container); init(); $input .click(function(){ if (!inFocus) { $container.toggle(); } }) .focus(function(){ if ($container.not(':visible')) { inFocus = true; $container.show(); } }) .keydown(function(event) { switch(event.keyCode) { case 38: // up event.preventDefault(); moveSelect(-1); break; case 40: // down event.preventDefault(); moveSelect(1); break; //case 9: // tab case 13: // return event.preventDefault(); // seems not working in mac ! $('li.'+opt.hoverClass).trigger('click'); break; case 27: //escape hideMe(); break; } }) .blur(function() { if ($container.is(':visible') && hasfocus > 0 ) { if(opt.debug) console.log('container visible and has focus') } else { hideMe(); } }); function hideMe() { hasfocus = 0; $container.hide(); } function init() { $container.append(getSelectOptions($input.attr('id'))).hide(); var width = $input.css('width'); $container.width(width); } function setupContainer(options) { var container = document.createElement("div"); $container = $(container); $container.attr('id', elm_id+'_container'); $container.addClass(options.containerClass); return $container; } function setupInput(options) { var input = document.createElement("input"); var $input = $(input); $input.attr("id", elm_id+"_input"); $input.attr("type", "text"); $input.addClass(options.inputClass); $input.attr("autocomplete", "off"); $input.attr("readonly", "readonly"); $input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie return $input; } function moveSelect(step) { var lis = $("li", $container); if (!lis) return; active += step; if (active < 0) { active = 0; } else if (active >= lis.size()) { active = lis.size() - 1; } lis.removeClass(opt.hoverClass); $(lis[active]).addClass(opt.hoverClass); } function setCurrent() { var li = $("li."+opt.currentClass, $container).get(0); var ar = (''+li.id).split('_'); var el = ar[ar.length-1]; $select.val(el); $input.val($(li).html()); return true; } // select value function getCurrentSelected() { return $select.val(); } // input value function getCurrentValue() { return $input.val(); } function getSelectOptions(parentid) { var select_options = new Array(); var ul = document.createElement('ul'); $select.children('option').each(function() { var li = document.createElement('li'); li.setAttribute('id', parentid + '_' + $(this).val()); li.innerHTML = $(this).html(); if ($(this).is(':selected')) { $input.val($(this).html()); $(li).addClass(opt.currentClass); } ul.appendChild(li); $(li) .mouseover(function(event) { hasfocus = 1; if (opt.debug) console.log('over on : '+this.id); jQuery(event.target, $container).addClass(opt.hoverClass); }) .mouseout(function(event) { hasfocus = -1; if (opt.debug) console.log('out on : '+this.id); jQuery(event.target, $container).removeClass(opt.hoverClass); }) .click(function(event) { var fl = $('li.'+opt.hoverClass, $container).get(0); if (opt.debug) console.log('click on :'+this.id); $('li.'+opt.currentClass).removeClass(opt.currentClass); $(this).addClass(opt.currentClass); setCurrent(); hideMe(); }); }); return ul; } };
JavaScript
/************************ jquery-timepicker http://jonthornton.github.com/jquery-timepicker/ requires jQuery 1.7+ ************************/ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Browser globals factory(jQuery); } }(function ($) { var _baseDate = _generateBaseDate(); var _ONE_DAY = 86400; var _defaults = { className: null, minTime: null, maxTime: null, durationTime: null, step: 30, showDuration: false, timeFormat: 'g:ia', scrollDefaultNow: false, scrollDefaultTime: false, selectOnBlur: false, forceRoundTime: false, appendTo: 'body' }; var _lang = { decimal: '.', mins: 'mins', hr: 'hr', hrs: 'hrs' }; var methods = { init: function(options) { return this.each(function() { var self = $(this); // convert dropdowns to text input if (self[0].tagName == 'SELECT') { var attrs = { 'type': 'text', 'value': self.val() }; var raw_attrs = self[0].attributes; for (var i=0; i < raw_attrs.length; i++) { attrs[raw_attrs[i].nodeName] = raw_attrs[i].nodeValue; } var input = $('<input />', attrs); self.replaceWith(input); self = input; } var settings = $.extend({}, _defaults); if (options) { settings = $.extend(settings, options); } if (settings.minTime) { settings.minTime = _time2int(settings.minTime); } if (settings.maxTime) { settings.maxTime = _time2int(settings.maxTime); } if (settings.durationTime) { settings.durationTime = _time2int(settings.durationTime); } if (settings.lang) { _lang = $.extend(_lang, settings.lang); } self.data('timepicker-settings', settings); self.prop('autocomplete', 'off'); self.on('click.timepicker focus.timepicker', methods.show); self.on('blur.timepicker', _formatValue); self.on('keydown.timepicker', _keyhandler); self.addClass('ui-timepicker-input'); _formatValue.call(self.get(0)); }); }, show: function(e) { var self = $(this); if ('ontouchstart' in document) { // block the keyboard on mobile devices self.blur(); } var list = self.data('timepicker-list'); // check if input is readonly if (self.prop('readonly')) { return; } // check if list needs to be rendered if (!list || list.length === 0) { _render(self); list = self.data('timepicker-list'); } // check if a flag was set to close this picker if (self.hasClass('ui-timepicker-hideme')) { self.removeClass('ui-timepicker-hideme'); list.hide(); return; } if (list.is(':visible')) { return; } // make sure other pickers are hidden methods.hide(); if ((self.offset().top + self.outerHeight(true) + list.outerHeight()) > $(window).height() + $(window).scrollTop()) { // position the dropdown on top list.css({ 'left':(self.offset().left), 'top': self.offset().top - list.outerHeight() }); } else { // put it under the input list.css({ 'left':(self.offset().left), 'top': self.offset().top + self.outerHeight() }); } list.show(); var settings = self.data('timepicker-settings'); // position scrolling var selected = list.find('.ui-timepicker-selected'); if (!selected.length) { if (self.val()) { selected = _findRow(self, list, _time2int(self.val())); } else if (settings.scrollDefaultNow) { selected = _findRow(self, list, _time2int(new Date())); } else if (settings.scrollDefaultTime !== false) { selected = _findRow(self, list, _time2int(settings.scrollDefaultTime)); } } if (selected && selected.length) { var topOffset = list.scrollTop() + selected.position().top - selected.outerHeight(); list.scrollTop(topOffset); } else { list.scrollTop(0); } _attachCloseHandler(); self.trigger('showTimepicker'); }, hide: function(e) { $('.ui-timepicker-list:visible').each(function() { var list = $(this); var self = list.data('timepicker-input'); var settings = self.data('timepicker-settings'); if (settings && settings.selectOnBlur) { _selectValue(self); } list.hide(); self.trigger('hideTimepicker'); }); }, option: function(key, value) { var self = $(this); var settings = self.data('timepicker-settings'); var list = self.data('timepicker-list'); if (typeof key == 'object') { settings = $.extend(settings, key); } else if (typeof key == 'string' && typeof value != 'undefined') { settings[key] = value; } else if (typeof key == 'string') { return settings[key]; } if (settings.minTime) { settings.minTime = _time2int(settings.minTime); } if (settings.maxTime) { settings.maxTime = _time2int(settings.maxTime); } if (settings.durationTime) { settings.durationTime = _time2int(settings.durationTime); } self.data('timepicker-settings', settings); if (list) { list.remove(); self.data('timepicker-list', false); } }, getSecondsFromMidnight: function() { return _time2int($(this).val()); }, getTime: function() { return new Date(_baseDate.valueOf() + (_time2int($(this).val())*1000)); }, setTime: function(value) { var self = $(this); var prettyTime = _int2time(_time2int(value), self.data('timepicker-settings').timeFormat); self.val(prettyTime); }, remove: function() { var self = $(this); // check if this element is a timepicker if (!self.hasClass('ui-timepicker-input')) { return; } self.removeAttr('autocomplete', 'off'); self.removeClass('ui-timepicker-input'); self.removeData('timepicker-settings'); self.off('.timepicker'); // timepicker-list won't be present unless the user has interacted with this timepicker if (self.data('timepicker-list')) { self.data('timepicker-list').remove(); } self.removeData('timepicker-list'); } }; // private methods function _render(self) { var settings = self.data('timepicker-settings'); var list = self.data('timepicker-list'); if (list && list.length) { list.remove(); self.data('timepicker-list', false); } list = $('<ul />', { 'tabindex': -1, 'class': 'ui-timepicker-list' }); if (settings.className) { list.addClass(settings.className); } list.css({'display':'none', 'position': 'absolute' }); if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) { list.addClass('ui-timepicker-with-duration'); } var durStart = (settings.durationTime !== null) ? settings.durationTime : settings.minTime; var start = (settings.minTime !== null) ? settings.minTime : 0; var end = (settings.maxTime !== null) ? settings.maxTime : (start + _ONE_DAY - 1); if (end <= start) { // make sure the end time is greater than start time, otherwise there will be no list to show end += _ONE_DAY; } for (var i=start; i <= end; i += settings.step*60) { var timeInt = i%_ONE_DAY; var row = $('<li />'); row.data('time', timeInt); row.text(_int2time(timeInt, settings.timeFormat)); if ((settings.minTime !== null || settings.durationTime !== null) && settings.showDuration) { var duration = $('<span />'); duration.addClass('ui-timepicker-duration'); duration.text(' ('+_int2duration(i - durStart)+')'); row.append(duration); } list.append(row); } list.data('timepicker-input', self); self.data('timepicker-list', list); var appendTo = settings.appendTo; if (typeof appendTo === 'string') { appendTo = $(appendTo); } else if (typeof appendTo === 'function') { appendTo = appendTo(self); } appendTo.append(list); _setSelected(self, list); list.on('click', 'li', function(e) { self.addClass('ui-timepicker-hideme'); self[0].focus(); // make sure only the clicked row is selected list.find('li').removeClass('ui-timepicker-selected'); $(this).addClass('ui-timepicker-selected'); _selectValue(self); list.hide(); }); } function _generateBaseDate() { var _baseDate = new Date(); var _currentTimezoneOffset = _baseDate.getTimezoneOffset()*60000; _baseDate.setHours(0); _baseDate.setMinutes(0); _baseDate.setSeconds(0); var _baseDateTimezoneOffset = _baseDate.getTimezoneOffset()*60000; return new Date(_baseDate.valueOf() - _baseDateTimezoneOffset + _currentTimezoneOffset); } function _attachCloseHandler() { if ('ontouchstart' in document) { $('body').on('touchstart.ui-timepicker', _closeHandler); } else { $('body').on('mousedown.ui-timepicker', _closeHandler); $(window).on('scroll.ui-timepicker', _closeHandler); } } // event handler to decide whether to close timepicker function _closeHandler(e) { var target = $(e.target); var input = target.closest('.ui-timepicker-input'); if (input.length === 0 && target.closest('.ui-timepicker-list').length === 0) { methods.hide(); } $('body').unbind('.ui-timepicker'); $(window).unbind('.ui-timepicker'); } function _findRow(self, list, value) { if (!value && value !== 0) { return false; } var settings = self.data('timepicker-settings'); var out = false; var halfStep = settings.step*30; // loop through the menu items list.find('li').each(function(i, obj) { var jObj = $(obj); var offset = jObj.data('time') - value; // check if the value is less than half a step from each row if (Math.abs(offset) < halfStep || offset == halfStep) { out = jObj; return false; } }); return out; } function _setSelected(self, list) { var timeValue = _time2int(self.val()); var selected = _findRow(self, list, timeValue); if (selected) selected.addClass('ui-timepicker-selected'); } function _formatValue() { if (this.value === '') { return; } var self = $(this); var seconds = _time2int(this.value); if (seconds === null) { self.trigger('timeFormatError'); return; } var settings = self.data('timepicker-settings'); if (settings.forceRoundTime) { var offset = seconds % (settings.step*60); // step is in minutes if (offset >= settings.step*30) { // if offset is larger than a half step, round up seconds += (settings.step*60) - offset; } else { // round down seconds -= offset; } } var prettyTime = _int2time(seconds, settings.timeFormat); self.val(prettyTime); } function _keyhandler(e) { var self = $(this); var list = self.data('timepicker-list'); if (!list.is(':visible')) { if (e.keyCode == 40) { self.focus(); } else { return true; } } switch (e.keyCode) { case 13: // return _selectValue(self); methods.hide.apply(this); e.preventDefault(); return false; case 38: // up var selected = list.find('.ui-timepicker-selected'); if (!selected.length) { list.children().each(function(i, obj) { if ($(obj).position().top > 0) { selected = $(obj); return false; } }); selected.addClass('ui-timepicker-selected'); } else if (!selected.is(':first-child')) { selected.removeClass('ui-timepicker-selected'); selected.prev().addClass('ui-timepicker-selected'); if (selected.prev().position().top < selected.outerHeight()) { list.scrollTop(list.scrollTop() - selected.outerHeight()); } } break; case 40: // down selected = list.find('.ui-timepicker-selected'); if (selected.length === 0) { list.children().each(function(i, obj) { if ($(obj).position().top > 0) { selected = $(obj); return false; } }); selected.addClass('ui-timepicker-selected'); } else if (!selected.is(':last-child')) { selected.removeClass('ui-timepicker-selected'); selected.next().addClass('ui-timepicker-selected'); if (selected.next().position().top + 2*selected.outerHeight() > list.outerHeight()) { list.scrollTop(list.scrollTop() + selected.outerHeight()); } } break; case 27: // escape list.find('li').removeClass('ui-timepicker-selected'); list.hide(); break; case 9: //tab methods.hide(); break; case 16: case 17: case 18: case 19: case 20: case 33: case 34: case 35: case 36: case 37: case 39: case 45: return; default: list.find('li').removeClass('ui-timepicker-selected'); return; } } function _selectValue(self) { var settings = self.data('timepicker-settings'); var list = self.data('timepicker-list'); var timeValue = null; var cursor = list.find('.ui-timepicker-selected'); if (cursor.length) { // selected value found timeValue = cursor.data('time'); } else if (self.val()) { // no selected value; fall back on input value timeValue = _time2int(self.val()); _setSelected(self, list); } if (timeValue !== null) { var timeString = _int2time(timeValue, settings.timeFormat); self.val(timeString); } self.trigger('change').trigger('changeTime'); } function _int2duration(seconds) { var minutes = Math.round(seconds/60); var duration; if (Math.abs(minutes) < 60) { duration = [minutes, _lang.mins]; } else if (minutes == 60) { duration = ['1', _lang.hr]; } else { var hours = (minutes/60).toFixed(1); if (_lang.decimal != '.') hours = hours.replace('.', _lang.decimal); duration = [hours, _lang.hrs]; } return duration.join(' '); } function _int2time(seconds, format) { if (seconds === null) { return; } var time = new Date(_baseDate.valueOf() + (seconds*1000)); var output = ''; var hour, code; for (var i=0; i<format.length; i++) { code = format.charAt(i); switch (code) { case 'a': output += (time.getHours() > 11) ? 'pm' : 'am'; break; case 'A': output += (time.getHours() > 11) ? 'PM' : 'AM'; break; case 'g': hour = time.getHours() % 12; output += (hour === 0) ? '12' : hour; break; case 'G': output += time.getHours(); break; case 'h': hour = time.getHours() % 12; if (hour !== 0 && hour < 10) { hour = '0'+hour; } output += (hour === 0) ? '12' : hour; break; case 'H': hour = time.getHours(); output += (hour > 9) ? hour : '0'+hour; break; case 'i': var minutes = time.getMinutes(); output += (minutes > 9) ? minutes : '0'+minutes; break; case 's': seconds = time.getSeconds(); output += (seconds > 9) ? seconds : '0'+seconds; break; default: output += code; } } return output; } function _time2int(timeString) { if (timeString === '') return null; if (timeString+0 == timeString) return timeString; if (typeof(timeString) == 'object') { timeString = timeString.getHours()+':'+timeString.getMinutes()+':'+timeString.getSeconds(); } var d = new Date(0); var time = timeString.toLowerCase().match(/(\d{1,2})(?::(\d{1,2}))?(?::(\d{2}))?\s*([pa]?)/); if (!time) { return null; } var hour = parseInt(time[1]*1, 10); var hours; if (time[4]) { if (hour == 12) { hours = (time[4] == 'p') ? 12 : 0; } else { hours = (hour + (time[4] == 'p' ? 12 : 0)); } } else { hours = hour; } var minutes = ( time[2]*1 || 0 ); var seconds = ( time[3]*1 || 0 ); return hours*3600 + minutes*60 + seconds; } // Plugin entry $.fn.timepicker = function(method) { if(methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if(typeof method === "object" || !method) { return methods.init.apply(this, arguments); } else { $.error("Method "+ method + " does not exist on jQuery.timepicker"); } }; }));
JavaScript
/************************************************************************ ************************************************************************* @Name : jNotify - jQuery Plugin @Revison : 2.1 @Date : 18/01/2011 @Author: ALPIXEL (www.myjqueryplugins.com - www.alpixel.fr) @Support: FF, IE7, IE8, MAC Firefox, MAC Safari @License : Open Source - MIT License : http://www.opensource.org/licenses/mit-license.php ************************************************************************** *************************************************************************/ (function($) { $.jNotify = { defaults: { /** VARS - OPTIONS **/ autoHide: true, // Notify box auto-close after 'TimeShown' ms ? clickOverlay: false, // if 'clickOverlay' = false, close the notice box on the overlay click ? MinWidth: 200, // min-width CSS property TimeShown: 1500, // Box shown during 'TimeShown' ms ShowTimeEffect: 200, // duration of the Show Effect HideTimeEffect: 200, // duration of the Hide effect LongTrip: 15, // in pixel, length of the move effect when show and hide HorizontalPosition: 'center', // left, center, right VerticalPosition: 'top', // top, center, bottom ShowOverlay: true, // show overlay behind the notice ? ColorOverlay: '#000', // color of the overlay OpacityOverlay: 0.3, // opacity of the overlay /** METHODS - OPTIONS **/ onClosed: null, onCompleted: null }, /*****************/ /** Init Method **/ /*****************/ init: function(msg, options, id) { opts = $.extend({}, $.jNotify.defaults, options); /** Box **/ if ($("#" + id).length == 0) $Div = $.jNotify._construct(id, msg); // Width of the Brower WidthDoc = parseInt($(window).width()); HeightDoc = parseInt($(window).height()); // Scroll Position ScrollTop = parseInt($(window).scrollTop()); ScrollLeft = parseInt($(window).scrollLeft()); // Position of the jNotify Box posTop = $.jNotify.vPos(opts.VerticalPosition); posLeft = $.jNotify.hPos(opts.HorizontalPosition); // Show the jNotify Box if (opts.ShowOverlay && $("#jOverlay").length == 0) $.jNotify._showOverlay($Div); $.jNotify._show(msg); }, /*******************/ /** Construct DOM **/ /*******************/ _construct: function(id, msg) { $Div = $('<div id="' + id + '"/>') .css({ opacity: 0, minWidth: opts.MinWidth }) .html(msg) .appendTo('body'); return $Div; }, /**********************/ /** Postions Methods **/ /**********************/ vPos: function(pos) { switch (pos) { case 'top': var vPos = ScrollTop + parseInt($Div.outerHeight(true) / 2); break; case 'center': var vPos = ScrollTop + (HeightDoc / 2) - (parseInt($Div.outerHeight(true)) / 2); break; case 'bottom': var vPos = ScrollTop + HeightDoc - parseInt($Div.outerHeight(true)); break; } return vPos; }, hPos: function(pos) { switch (pos) { case 'left': var hPos = ScrollLeft; break; case 'center': var hPos = ScrollLeft + (WidthDoc / 2) - (parseInt($Div.outerWidth(true)) / 2); break; case 'right': var hPos = ScrollLeft + WidthDoc - parseInt($Div.outerWidth(true)); break; } return hPos; }, /*********************/ /** Show Div Method **/ /*********************/ _show: function(msg) { $Div .css({ top: posTop, left: posLeft }); switch (opts.VerticalPosition) { case 'top': $Div.animate({ top: posTop + opts.LongTrip, opacity: 1 }, opts.ShowTimeEffect, function() { if (opts.onCompleted) opts.onCompleted(); }); if (opts.autoHide) $.jNotify._close(); else $Div.css('cursor', 'pointer').click(function(e) { $.jNotify._close(); }); break; case 'center': $Div.animate({ opacity: 1 }, opts.ShowTimeEffect, function() { if (opts.onCompleted) opts.onCompleted(); }); if (opts.autoHide) $.jNotify._close(); else $Div.css('cursor', 'pointer').click(function(e) { $.jNotify._close(); }); break; case 'bottom': $Div.animate({ top: posTop - opts.LongTrip, opacity: 1 }, opts.ShowTimeEffect, function() { if (opts.onCompleted) opts.onCompleted(); }); if (opts.autoHide) $.jNotify._close(); else $Div.css('cursor', 'pointer').click(function(e) { $.jNotify._close(); }); break; } }, _showOverlay: function(el) { var overlay = $('<div id="jOverlay" />') .css({ backgroundColor: opts.ColorOverlay, opacity: opts.OpacityOverlay }) .appendTo('body') .show(); if (opts.clickOverlay) overlay.click(function(e) { e.preventDefault(); opts.TimeShown = 0; // Thanks to Guillaume M. $.jNotify._close(); }); }, _close: function() { switch (opts.VerticalPosition) { case 'top': if (!opts.autoHide) opts.TimeShown = 0; $Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M. top: posTop - opts.LongTrip, opacity: 0 }, opts.HideTimeEffect, function() { $(this).remove(); if (opts.ShowOverlay && $("#jOverlay").length > 0) $("#jOverlay").remove(); if (opts.onClosed) opts.onClosed(); }); break; case 'center': if (!opts.autoHide) opts.TimeShown = 0; $Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M. opacity: 0 }, opts.HideTimeEffect, function() { $(this).remove(); if (opts.ShowOverlay && $("#jOverlay").length > 0) $("#jOverlay").remove(); if (opts.onClosed) opts.onClosed(); }); break; case 'bottom': if (!opts.autoHide) opts.TimeShown = 0; $Div.stop(true, true).delay(opts.TimeShown).animate({ // Tanks to Guillaume M. top: posTop + opts.LongTrip, opacity: 0 }, opts.HideTimeEffect, function() { $(this).remove(); if (opts.ShowOverlay && $("#jOverlay").length > 0) $("#jOverlay").remove(); if (opts.onClosed) opts.onClosed(); }); break; } }, _isReadable: function(id) { if ($('#' + id).length > 0) return false; else return true; } }; /** Init method **/ jNotify = function(msg, options) { if ($.jNotify._isReadable('jNotify')) $.jNotify.init(msg, options, 'jNotify'); }; jSuccess = function(msg, options) { if ($.jNotify._isReadable('jSuccess')) $.jNotify.init(msg, options, 'jSuccess'); }; jError = function(msg, options) { if ($.jNotify._isReadable('jError')) $.jNotify.init(msg, options, 'jError'); }; })(jQuery);
JavaScript
/* * jQuery showLoading plugin v1.0 * * Copyright (c) 2009 Jim Keller * Context - http://www.contextllc.com * * Dual licensed under the MIT and GPL licenses. * */ jQuery.fn.showLoading = function(options) { var indicatorID; var settings = { 'addClass': '', 'beforeShow': '', 'afterShow': '', 'hPos': 'center', 'vPos': 'center', 'indicatorZIndex' : 5001, 'overlayZIndex': 5000, 'parent': '', 'marginTop': 0, 'marginLeft': 0, 'overlayWidth': null, 'overlayHeight': null }; jQuery.extend(settings, options); var loadingDiv = jQuery('<div></div>'); var overlayDiv = jQuery('<div></div>'); // // Set up ID and classes // if ( settings.indicatorID ) { indicatorID = settings.indicatorID; } else { indicatorID = jQuery(this).attr('id'); } jQuery(loadingDiv).attr('id', 'loading-indicator-' + indicatorID ); jQuery(loadingDiv).addClass('loading-indicator'); if ( settings.addClass ){ jQuery(loadingDiv).addClass(settings.addClass); } // // Create the overlay // jQuery(overlayDiv).css('display', 'none'); // Append to body, otherwise position() doesn't work on Webkit-based browsers jQuery(document.body).append(overlayDiv); // // Set overlay classes // jQuery(overlayDiv).attr('id', 'loading-indicator-' + indicatorID + '-overlay'); jQuery(overlayDiv).addClass('loading-indicator-overlay'); if ( settings.addClass ){ jQuery(overlayDiv).addClass(settings.addClass + '-overlay'); } // // Set overlay position // var overlay_width; var overlay_height; var border_top_width = jQuery(this).css('border-top-width'); var border_left_width = jQuery(this).css('border-left-width'); // // IE will return values like 'medium' as the default border, // but we need a number // border_top_width = isNaN(parseInt(border_top_width)) ? 0 : border_top_width; border_left_width = isNaN(parseInt(border_left_width)) ? 0 : border_left_width; var overlay_left_pos = jQuery(this).offset().left + parseInt(border_left_width); var overlay_top_pos = jQuery(this).offset().top + parseInt(border_top_width); if ( settings.overlayWidth !== null ) { overlay_width = settings.overlayWidth; } else { overlay_width = parseInt(jQuery(this).width()) + parseInt(jQuery(this).css('padding-right')) + parseInt(jQuery(this).css('padding-left')); } if ( settings.overlayHeight !== null ) { overlay_height = settings.overlayWidth; } else { overlay_height = parseInt(jQuery(this).height()) + parseInt(jQuery(this).css('padding-top')) + parseInt(jQuery(this).css('padding-bottom')); } jQuery(overlayDiv).css('width', overlay_width.toString() + 'px'); jQuery(overlayDiv).css('height', overlay_height.toString() + 'px'); jQuery(overlayDiv).css('left', overlay_left_pos.toString() + 'px'); jQuery(overlayDiv).css('position', 'absolute'); jQuery(overlayDiv).css('top', overlay_top_pos.toString() + 'px' ); jQuery(overlayDiv).css('z-index', settings.overlayZIndex); // // Set any custom overlay CSS // if ( settings.overlayCSS ) { jQuery(overlayDiv).css ( settings.overlayCSS ); } // // We have to append the element to the body first // or .width() won't work in Webkit-based browsers (e.g. Chrome, Safari) // jQuery(loadingDiv).css('display', 'none'); jQuery(document.body).append(loadingDiv); jQuery(loadingDiv).css('position', 'absolute'); jQuery(loadingDiv).css('z-index', settings.indicatorZIndex); // // Set top margin // var indicatorTop = overlay_top_pos; if ( settings.marginTop ) { indicatorTop += parseInt(settings.marginTop); } var indicatorLeft = overlay_left_pos; if ( settings.marginLeft ) { indicatorLeft += parseInt(settings.marginTop); } // // set horizontal position // if ( settings.hPos.toString().toLowerCase() == 'center' ) { jQuery(loadingDiv).css('left', (indicatorLeft + ((jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width())) / 2)).toString() + 'px'); } else if ( settings.hPos.toString().toLowerCase() == 'left' ) { jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(jQuery(overlayDiv).css('margin-left'))).toString() + 'px'); } else if ( settings.hPos.toString().toLowerCase() == 'right' ) { jQuery(loadingDiv).css('left', (indicatorLeft + (jQuery(overlayDiv).width() - parseInt(jQuery(loadingDiv).width()))).toString() + 'px'); } else { jQuery(loadingDiv).css('left', (indicatorLeft + parseInt(settings.hPos)).toString() + 'px'); } // // set vertical position // if ( settings.vPos.toString().toLowerCase() == 'center' ) { jQuery(loadingDiv).css('top', (indicatorTop + ((jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height())) / 2)).toString() + 'px'); } else if ( settings.vPos.toString().toLowerCase() == 'top' ) { jQuery(loadingDiv).css('top', indicatorTop.toString() + 'px'); } else if ( settings.vPos.toString().toLowerCase() == 'bottom' ) { jQuery(loadingDiv).css('top', (indicatorTop + (jQuery(overlayDiv).height() - parseInt(jQuery(loadingDiv).height()))).toString() + 'px'); } else { jQuery(loadingDiv).css('top', (indicatorTop + parseInt(settings.vPos)).toString() + 'px' ); } // // Set any custom css for loading indicator // if ( settings.css ) { jQuery(loadingDiv).css ( settings.css ); } // // Set up callback options // var callback_options = { 'overlay': overlayDiv, 'indicator': loadingDiv, 'element': this }; // // beforeShow callback // if ( typeof(settings.beforeShow) == 'function' ) { settings.beforeShow( callback_options ); } // // Show the overlay // jQuery(overlayDiv).show(); // // Show the loading indicator // jQuery(loadingDiv).show(); // // afterShow callback // if ( typeof(settings.afterShow) == 'function' ) { settings.afterShow( callback_options ); } return this; }; jQuery.fn.hideLoading = function(options) { var settings = {}; jQuery.extend(settings, options); if ( settings.indicatorID ) { indicatorID = settings.indicatorID; } else { indicatorID = jQuery(this).attr('id'); } jQuery(document.body).find('#loading-indicator-' + indicatorID ).remove(); jQuery(document.body).find('#loading-indicator-' + indicatorID + '-overlay' ).remove(); return this; };
JavaScript
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;b.axis!==void 0&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);b.wheelDeltaY!==void 0&&(g=b.wheelDeltaY/120);b.wheelDeltaX!==void 0&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]= d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,false);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
JavaScript
/* * Inline Form Validation Engine 2.6, jQuery plugin * * Copyright(c) 2010, Cedric Dugas * http://www.position-absolute.com * * 2.0 Rewrite by Olivier Refalo * http://www.crionics.com * * Form validation engine allowing custom regex rules to be added. * Licensed under the MIT License */ (function($) { "use strict"; var methods = { /** * Kind of the constructor, called before any action * @param {Map} user options */ init: function(options) { var form = this; if (!form.data('jqv') || form.data('jqv') == null) { options = methods._saveOptions(form, options); // bind all formError elements to close on click $(".formError").live("click", function() { $(this).fadeOut(150, function() { // remove prompt once invisible $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); }); } return this; }, /** * Attachs jQuery.validationEngine to form.submit and field.blur events * Takes an optional params: a list of options * ie. jQuery("#formID1").validationEngine('attach', {promptPosition : "centerRight"}); */ attach: function(userOptions) { if (!$(this).is("form")) { alert("Sorry, jqv.attach() only applies to a form"); return this; } var form = this; var options; if (userOptions) options = methods._saveOptions(form, userOptions); else options = form.data('jqv'); options.validateAttribute = (form.find("[data-validation-engine*=validate]").length) ? "data-validation-engine" : "class"; if (options.binded) { // bind fields form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").not("[type=radio]").not(".datepicker").bind(options.validationEventTrigger, methods._onFieldEvent); form.find("[" + options.validateAttribute + "*=validate][type=checkbox],[" + options.validateAttribute + "*=validate][type=radio]").bind("click", methods._onFieldEvent); form.find("[" + options.validateAttribute + "*=validate][class*=datepicker]").bind(options.validationEventTrigger, { "delay": 300 }, methods._onFieldEvent); } if (options.autoPositionUpdate) { $(window).bind("resize", { "noAnimation": true, "formElem": form }, methods.updatePromptsPosition); } // bind form.submit form.bind("submit", methods._onSubmitEvent); return this; }, /** * Unregisters any bindings that may point to jQuery.validaitonEngine */ detach: function() { if (!$(this).is("form")) { alert("Sorry, jqv.detach() only applies to a form"); return this; } var form = this; var options = form.data('jqv'); // unbind fields form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").unbind(options.validationEventTrigger, methods._onFieldEvent); form.find("[" + options.validateAttribute + "*=validate][type=checkbox],[class*=validate][type=radio]").unbind("click", methods._onFieldEvent); // unbind form.submit form.unbind("submit", methods.onAjaxFormComplete); // unbind live fields (kill) form.find("[" + options.validateAttribute + "*=validate]").not("[type=checkbox]").die(options.validationEventTrigger, methods._onFieldEvent); form.find("[" + options.validateAttribute + "*=validate][type=checkbox]").die("click", methods._onFieldEvent); // unbind form.submit form.die("submit", methods.onAjaxFormComplete); form.removeData('jqv'); if (options.autoPositionUpdate) $(window).unbind("resize", methods.updatePromptsPosition); return this; }, /** * Validates either a form or a list of fields, shows prompts accordingly. * Note: There is no ajax form validation with this method, only field ajax validation are evaluated * * @return true if the form validates, false if it fails */ validate: function() { var element = $(this); var valid = null; if (element.is("form") && !element.hasClass('validating')) { element.addClass('validating'); var options = element.data('jqv'); valid = methods._validateFields(this); // If the form doesn't validate, clear the 'validating' class before the user has a chance to submit again setTimeout(function() { element.removeClass('validating'); }, 100); if (valid && options.onFormSuccess) { options.onFormSuccess(); } else if (!valid && options.onFormFailure) { options.onFormFailure(); } } else if (element.is('form')) { element.removeClass('validating'); } else { // field validation var form = element.closest('form'); var options = form.data('jqv'); valid = methods._validateField(element, options); if (valid && options.onFieldSuccess) options.onFieldSuccess(); else if (options.onFieldFailure && options.InvalidFields.length > 0) { options.onFieldFailure(); } } return valid; }, /** * Redraw prompts position, useful when you change the DOM state when validating */ updatePromptsPosition: function(event) { if (event && this == window) { var form = event.data.formElem; var noAnimation = event.data.noAnimation; } else var form = $(this.closest('form')); var options = form.data('jqv'); // No option, take default one form.find('[' + options.validateAttribute + '*=validate]').not(":disabled").each(function() { var field = $(this); if (options.prettySelect && field.is(":hidden")) field = form.find("#" + options.usePrefix + field.attr('id') + options.useSuffix); var prompt = methods._getPrompt(field); var promptText = $(prompt).find(".formErrorContent").html(); if (prompt) methods._updatePrompt(field, $(prompt), promptText, undefined, false, options, noAnimation); }); return this; }, /** * Displays a prompt on a element. * Note that the element needs an id! * * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {String} possible values topLeft, topRight, bottomLeft, centerRight, bottomRight */ showPrompt: function(promptText, type, promptPosition, showArrow) { var form = this.closest('form'); var options = form.data('jqv'); // No option, take default one if (!options) options = methods._saveOptions(this, options); if (promptPosition) options.promptPosition = promptPosition; options.showArrow = showArrow == true; methods._showPrompt(this, promptText, type, false, options); return this; }, /** * Closes form error prompts, CAN be invidual */ hide: function() { var form = $(this).closest('form'); var options = form.data('jqv'); var fadeDuration = (options && options.fadeDuration) ? options.fadeDuration : 0.3; var closingtag; if ($(this).is("form")) { closingtag = "parentForm" + methods._getClassName($(this).attr("id")); } else { closingtag = methods._getClassName($(this).attr("id")) + "formError"; } $('.' + closingtag).fadeTo(fadeDuration, 0.3, function() { $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); return this; }, /** * Closes all error prompts on the page */ hideAll: function() { var form = this; var options = form.data('jqv'); var duration = options ? options.fadeDuration : 0.3; $('.formError').fadeTo(duration, 0.3, function() { $(this).parent('.formErrorOuter').remove(); $(this).remove(); }); return this; }, /** * Typically called when user exists a field using tab or a mouse click, triggers a field * validation */ _onFieldEvent: function(event) { var field = $(this); var form = field.closest('form'); var options = form.data('jqv'); options.eventTrigger = "field"; // validate the current field window.setTimeout(function() { methods._validateField(field, options); if (options.InvalidFields.length == 0 && options.onFieldSuccess) { options.onFieldSuccess(); } else if (options.InvalidFields.length > 0 && options.onFieldFailure) { options.onFieldFailure(); } }, (event.data) ? event.data.delay : 0); }, /** * Called when the form is submited, shows prompts accordingly * * @param {jqObject} * form * @return false if form submission needs to be cancelled */ _onSubmitEvent: function() { var form = $(this); var options = form.data('jqv'); options.eventTrigger = "submit"; // validate each field // (- skip field ajax validation, not necessary IF we will perform an ajax form validation) var r = methods._validateFields(form); if (r && options.ajaxFormValidation) { methods._validateFormWithAjax(form, options); // cancel form auto-submission - process with async call onAjaxFormComplete return false; } if (options.onValidationComplete) { // !! ensures that an undefined return is interpreted as return false but allows a onValidationComplete() to possibly return true and have form continue processing return !!options.onValidationComplete(form, r); } return r; }, /** * Return true if the ajax field validations passed so far * @param {Object} options * @return true, is all ajax validation passed so far (remember ajax is async) */ _checkAjaxStatus: function(options) { var status = true; $.each(options.ajaxValidCache, function(key, value) { if (!value) { status = false; // break the each return false; } }); return status; }, /** * Return true if the ajax field is validated * @param {String} fieldid * @param {Object} options * @return true, if validation passed, false if false or doesn't exist */ _checkAjaxFieldStatus: function(fieldid, options) { return options.ajaxValidCache[fieldid] == true; }, /** * Validates form fields, shows prompts accordingly * * @param {jqObject} * form * @param {skipAjaxFieldValidation} * boolean - when set to true, ajax field validation is skipped, typically used when the submit button is clicked * * @return true if form is valid, false if not, undefined if ajax form validation is done */ _validateFields: function(form) { var options = form.data('jqv'); // this variable is set to true if an error is found var errorFound = false; // Trigger hook, start validation form.trigger("jqv.form.validating"); // first, evaluate status of non ajax fields var first_err = null; form.find('[' + options.validateAttribute + '*=validate]').not(":disabled").each(function() { var field = $(this); var names = []; if ($.inArray(field.attr('name'), names) < 0) { errorFound |= methods._validateField(field, options); if (errorFound && first_err == null) if (field.is(":hidden") && options.prettySelect) first_err = field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix); else first_err = field; if (options.doNotShowAllErrosOnSubmit) return false; names.push(field.attr('name')); //if option set, stop checking validation rules after one error is found if (options.showOneMessage == true && errorFound) { return false; } } }); // second, check to see if all ajax calls completed ok // errorFound |= !methods._checkAjaxStatus(options); // third, check status and scroll the container accordingly form.trigger("jqv.form.result", [errorFound]); if (errorFound) { if (options.scroll) { var destination = first_err.offset().top; var fixleft = first_err.offset().left; //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) var positionType = options.promptPosition; if (typeof (positionType) == 'string' && positionType.indexOf(":") != -1) positionType = positionType.substring(0, positionType.indexOf(":")); if (positionType != "bottomRight" && positionType != "bottomLeft") { var prompt_err = methods._getPrompt(first_err); if (prompt_err) { destination = prompt_err.offset().top; } } // get the position of the first error, there should be at least one, no need to check this //var destination = form.find(".formError:not('.greenPopup'):first").offset().top; if (options.isOverflown) { var overflowDIV = $(options.overflownDIV); if (!overflowDIV.length) return false; var scrollContainerScroll = overflowDIV.scrollTop(); var scrollContainerPos = -parseInt(overflowDIV.offset().top); destination += scrollContainerScroll + scrollContainerPos - 5; var scrollContainer = $(options.overflownDIV + ":not(:animated)"); scrollContainer.animate({ scrollTop: destination }, 1100, function() { if (options.focusFirstField) first_err.focus(); }); } else { $("body,html").stop().animate({ scrollTop: destination, scrollLeft: fixleft }, 1100, function() { if (options.focusFirstField) first_err.focus(); }); } } else if (options.focusFirstField) first_err.focus(); return false; } return true; }, /** * This method is called to perform an ajax form validation. * During this process all the (field, value) pairs are sent to the server which returns a list of invalid fields or true * * @param {jqObject} form * @param {Map} options */ _validateFormWithAjax: function(form, options) { var data = form.serialize(); var type = (options.ajaxmethod) ? options.ajaxmethod : "GET"; var url = (options.ajaxFormValidationURL) ? options.ajaxFormValidationURL : form.attr("action"); var dataType = (options.dataType) ? options.dataType : "json"; $.ajax({ type: type, url: url, cache: false, dataType: dataType, data: data, form: form, methods: methods, options: options, beforeSend: function() { return options.onBeforeAjaxFormValidation(form, options); }, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { if ((dataType == "json") && (json !== true)) { // getting to this case doesn't necessary means that the form is invalid // the server may return green or closing prompt actions // this flag helps figuring it out var errorInForm = false; for (var i = 0; i < json.length; i++) { var value = json[i]; var errorFieldId = value[0]; var errorField = $($("#" + errorFieldId)[0]); // make sure we found the element if (errorField.length == 1) { // promptText or selector var msg = value[2]; // if the field is valid if (value[1] == true) { if (msg == "" || !msg) { // if for some reason, status==true and error="", just close the prompt methods._closePrompt(errorField); } else { // the field is valid, but we are displaying a green prompt if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) msg = txt; } methods._showPrompt(errorField, msg, "pass", false, options, true); } } else { // the field is invalid, show the red error prompt errorInForm |= true; if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) msg = txt; } methods._showPrompt(errorField, msg, "", false, options, true); } } } options.onAjaxFormComplete(!errorInForm, form, json, options); } else options.onAjaxFormComplete(true, form, json, options); } }); }, /** * Validates field, shows prompts accordingly * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @param {Map} * user options * @return false if field is valid (It is inversed for *fields*, it return false on validate and true on errors.) */ _validateField: function(field, options, skipAjaxValidation) { if (!field.attr("id")) { field.attr("id", "form-validation-field-" + $.validationEngine.fieldIdCounter); ++$.validationEngine.fieldIdCounter; } if (field.is(":hidden") && !options.prettySelect || field.parent().is(":hidden")) return false; var rulesParsing = field.attr(options.validateAttribute); var getRules = /validate\[(.*)\]/.exec(rulesParsing); if (!getRules) return false; var str = getRules[1]; var rules = str.split(/\[|,|\]/); // true if we ran the ajax validation, tells the logic to stop messing with prompts var isAjaxValidator = false; var fieldName = field.attr("name"); var promptText = ""; var promptType = ""; var required = false; var limitErrors = false; options.isError = false; options.showArrow = true; // If the programmer wants to limit the amount of error messages per field, if (options.maxErrorsPerField > 0) { limitErrors = true; } var form = $(field.closest("form")); // Fix for adding spaces in the rules for (var i in rules) { rules[i] = rules[i].replace(" ", ""); // Remove any parsing errors if (rules[i] === '') { delete rules[i]; } } for (var i = 0, field_errors = 0; i < rules.length; i++) { // If we are limiting errors, and have hit the max, break if (limitErrors && field_errors >= options.maxErrorsPerField) { // If we haven't hit a required yet, check to see if there is one in the validation rules for this // field and that it's index is greater or equal to our current index if (!required) { var have_required = $.inArray('required', rules); required = (have_required != -1 && have_required >= i); } break; } var errorMsg = undefined; switch (rules[i]) { case "required": required = true; errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._required); break; case "custom": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._custom); break; case "groupRequired": // Check is its the first of group, if not, reload validation with first field // AND continue normal validation on present field var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]"; var firstOfGroup = form.find(classGroup).eq(0); if (firstOfGroup[0] != field[0]) { methods._validateField(firstOfGroup, options, skipAjaxValidation); options.showArrow = true; continue; } errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._groupRequired); if (errorMsg) required = true; options.showArrow = false; break; case "ajax": // AJAX defaults to returning it's loading message errorMsg = methods._ajax(field, rules, i, options); if (errorMsg) { promptType = "load"; } break; case "minSize": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minSize); break; case "maxSize": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxSize); break; case "min": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._min); break; case "max": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._max); break; case "past": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._past); break; case "future": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._future); break; case "dateRange": var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]"; options.firstOfGroup = form.find(classGroup).eq(0); options.secondOfGroup = form.find(classGroup).eq(1); //if one entry out of the pair has value then proceed to run through validation if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) { errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._dateRange); } if (errorMsg) required = true; options.showArrow = false; break; case "dateTimeRange": var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]"; options.firstOfGroup = form.find(classGroup).eq(0); options.secondOfGroup = form.find(classGroup).eq(1); //if one entry out of the pair has value then proceed to run through validation if (options.firstOfGroup[0].value || options.secondOfGroup[0].value) { errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._dateTimeRange); } if (errorMsg) required = true; options.showArrow = false; break; case "maxCheckbox": field = $(form.find("input[name='" + fieldName + "']")); errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._maxCheckbox); break; case "minCheckbox": field = $(form.find("input[name='" + fieldName + "']")); errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._minCheckbox); break; case "equals": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._equals); break; case "funcCall": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._funcCall); break; case "creditCard": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._creditCard); break; case "condRequired": errorMsg = methods._getErrorMessage(form, field, rules[i], rules, i, options, methods._condRequired); if (errorMsg !== undefined) { required = true; } break; default: } var end_validation = false; // If we were passed back an message object, check what the status was to determine what to do if (typeof errorMsg == "object") { switch (errorMsg.status) { case "_break": end_validation = true; break; // If we have an error message, set errorMsg to the error message case "_error": errorMsg = errorMsg.message; break; // If we want to throw an error, but not show a prompt, return early with true case "_error_no_prompt": return true; break; // Anything else we continue on default: break; } } // If it has been specified that validation should end now, break if (end_validation) { break; } // If we have a string, that means that we have an error, so add it to the error message. if (typeof errorMsg == 'string') { promptText += errorMsg + "<br/>"; options.isError = true; field_errors++; } } // If the rules required is not added, an empty field is not validated if (!required && field.val().length < 1) options.isError = false; // Hack for radio/checkbox group button, the validation go into the // first radio/checkbox of the group var fieldType = field.prop("type"); if ((fieldType == "radio" || fieldType == "checkbox") && form.find("input[name='" + fieldName + "']").size() > 1) { field = $(form.find("input[name='" + fieldName + "'][type!=hidden]:first")); options.showArrow = false; } if (field.is(":hidden") && options.prettySelect) { field = form.find("#" + options.usePrefix + methods._jqSelector(field.attr('id')) + options.useSuffix); } if (options.isError) { methods._showPrompt(field, promptText, promptType, false, options); } else { if (!isAjaxValidator) methods._closePrompt(field); } if (!isAjaxValidator) { field.trigger("jqv.field.result", [field, options.isError, promptText]); } /* Record error */ var errindex = $.inArray(field[0], options.InvalidFields); if (errindex == -1) { if (options.isError) options.InvalidFields.push(field[0]); } else if (!options.isError) { options.InvalidFields.splice(errindex, 1); } methods._handleStatusCssClasses(field, options); return options.isError; }, /** * Handling css classes of fields indicating result of validation * * @param {jqObject} * field * @param {Array[String]} * field's validation rules * @private */ _handleStatusCssClasses: function(field, options) { /* remove all classes */ if (options.addSuccessCssClassToField) field.removeClass(options.addSuccessCssClassToField); if (options.addFailureCssClassToField) field.removeClass(options.addFailureCssClassToField); /* Add classes */ if (options.addSuccessCssClassToField && !options.isError) field.addClass(options.addSuccessCssClassToField); if (options.addFailureCssClassToField && options.isError) field.addClass(options.addFailureCssClassToField); }, /******************** * _getErrorMessage * * @param form * @param field * @param rule * @param rules * @param i * @param options * @param originalValidationMethod * @return {*} * @private */ _getErrorMessage: function(form, field, rule, rules, i, options, originalValidationMethod) { // If we are using the custon validation type, build the index for the rule. // Otherwise if we are doing a function call, make the call and return the object // that is passed back. var beforeChangeRule = rule; if (rule == "custom") { var custom_validation_type_index = jQuery.inArray(rule, rules) + 1; var custom_validation_type = rules[custom_validation_type_index]; rule = "custom[" + custom_validation_type + "]"; } var element_classes = (field.attr("data-validation-engine")) ? field.attr("data-validation-engine") : field.attr("class"); var element_classes_array = element_classes.split(" "); // Call the original validation method. If we are dealing with dates or checkboxes, also pass the form var errorMsg; if (rule == "future" || rule == "past" || rule == "maxCheckbox" || rule == "minCheckbox") { errorMsg = originalValidationMethod(form, field, rules, i, options); } else { errorMsg = originalValidationMethod(field, rules, i, options); } // If the original validation method returned an error and we have a custom error message, // return the custom message instead. Otherwise return the original error message. if (errorMsg != undefined) { var custom_message = methods._getCustomErrorMessage($(field), element_classes_array, beforeChangeRule, options); if (custom_message) errorMsg = custom_message; } return errorMsg; }, _getCustomErrorMessage: function(field, classes, rule, options) { var custom_message = false; var validityProp = methods._validityProp[rule]; // If there is a validityProp for this rule, check to see if the field has an attribute for it if (validityProp != undefined) { custom_message = field.attr("data-errormessage-" + validityProp); // If there was an error message for it, return the message if (custom_message != undefined) return custom_message; } custom_message = field.attr("data-errormessage"); // If there is an inline custom error message, return it if (custom_message != undefined) return custom_message; var id = '#' + field.attr("id"); // If we have custom messages for the element's id, get the message for the rule from the id. // Otherwise, if we have custom messages for the element's classes, use the first class message we find instead. if (typeof options.custom_error_messages[id] != "undefined" && typeof options.custom_error_messages[id][rule] != "undefined") { custom_message = options.custom_error_messages[id][rule]['message']; } else if (classes.length > 0) { for (var i = 0; i < classes.length && classes.length > 0; i++) { var element_class = "." + classes[i]; if (typeof options.custom_error_messages[element_class] != "undefined" && typeof options.custom_error_messages[element_class][rule] != "undefined") { custom_message = options.custom_error_messages[element_class][rule]['message']; break; } } } if (!custom_message && typeof options.custom_error_messages[rule] != "undefined" && typeof options.custom_error_messages[rule]['message'] != "undefined") { custom_message = options.custom_error_messages[rule]['message']; } return custom_message; }, _validityProp: { "required": "value-missing", "custom": "custom-error", "groupRequired": "value-missing", "ajax": "custom-error", "minSize": "range-underflow", "maxSize": "range-overflow", "min": "range-underflow", "max": "range-overflow", "past": "type-mismatch", "future": "type-mismatch", "dateRange": "type-mismatch", "dateTimeRange": "type-mismatch", "maxCheckbox": "range-overflow", "minCheckbox": "range-underflow", "equals": "pattern-mismatch", "funcCall": "custom-error", "creditCard": "pattern-mismatch", "condRequired": "value-missing" }, /** * Required validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _required: function(field, rules, i, options) { switch (field.prop("type")) { case "text": case "password": case "textarea": case "file": case "select-one": case "select-multiple": default: if (!$.trim(field.val()) || field.val() == field.attr("data-validation-placeholder") || field.val() == field.attr("placeholder")) return options.allrules[rules[i]].alertText; break; case "radio": case "checkbox": var form = field.closest("form"); var name = field.attr("name"); if (form.find("input[name='" + name + "']:checked").size() == 0) { if (form.find("input[name='" + name + "']:visible").size() == 1) return options.allrules[rules[i]].alertTextCheckboxe; else return options.allrules[rules[i]].alertTextCheckboxMultiple; } break; } }, /** * Validate that 1 from the group field is required * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _groupRequired: function(field, rules, i, options) { var classGroup = "[" + options.validateAttribute + "*=" + rules[i + 1] + "]"; var isValid = false; // Check all fields from the group field.closest("form").find(classGroup).each(function() { if (!methods._required($(this), rules, i, options)) { isValid = true; return false; } }); if (!isValid) { return options.allrules[rules[i]].alertText; } }, /** * Validate rules * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _custom: function(field, rules, i, options) { var customRule = rules[i + 1]; var rule = options.allrules[customRule]; var fn; if (!rule) { alert("jqv:custom rule not found - " + customRule); return; } if (rule["regex"]) { var ex = rule.regex; if (!ex) { alert("jqv:custom regex not found - " + customRule); return; } var pattern = new RegExp(ex); if (!pattern.test(field.val())) return options.allrules[customRule].alertText; } else if (rule["func"]) { fn = rule["func"]; if (typeof (fn) !== "function") { alert("jqv:custom parameter 'function' is no function - " + customRule); return; } if (!fn(field, rules, i, options)) return options.allrules[customRule].alertText; } else { alert("jqv:custom type not allowed " + customRule); return; } }, /** * Validate custom function outside of the engine scope * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _funcCall: function(field, rules, i, options) { var functionName = rules[i + 1]; var fn; if (functionName.indexOf('.') > -1) { var namespaces = functionName.split('.'); var scope = window; while (namespaces.length) { scope = scope[namespaces.shift()]; } fn = scope; } else fn = window[functionName] || options.customFunctions[functionName]; if (typeof (fn) == 'function') return fn(field, rules, i, options); }, /** * Field match * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _equals: function(field, rules, i, options) { var equalsField = rules[i + 1]; if (field.val() != $("#" + equalsField).val()) return options.allrules.equals.alertText; }, /** * Check the maximum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxSize: function(field, rules, i, options) { var max = rules[i + 1]; var len = field.val().length; if (len > max) { var rule = options.allrules.maxSize; return rule.alertText + max + rule.alertText2; } }, /** * Check the minimum size (in characters) * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minSize: function(field, rules, i, options) { var min = rules[i + 1]; var len = field.val().length; if (len < min) { var rule = options.allrules.minSize; return rule.alertText + min + rule.alertText2; } }, /** * Check number minimum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _min: function(field, rules, i, options) { var min = parseFloat(rules[i + 1]); var len = parseFloat(field.val()); if (len < min) { var rule = options.allrules.min; if (rule.alertText2) return rule.alertText + min + rule.alertText2; return rule.alertText + min; } }, /** * Check number maximum value * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _max: function(field, rules, i, options) { var max = parseFloat(rules[i + 1]); var len = parseFloat(field.val()); if (len > max) { var rule = options.allrules.max; if (rule.alertText2) return rule.alertText + max + rule.alertText2; //orefalo: to review, also do the translations return rule.alertText + max; } }, /** * Checks date is in the past * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _past: function(form, field, rules, i, options) { var p = rules[i + 1]; var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']")); var pdate; if (p.toLowerCase() == "now") { pdate = new Date(); } else if (undefined != fieldAlt.val()) { if (fieldAlt.is(":disabled")) return; pdate = methods._parseDate(fieldAlt.val()); } else { pdate = methods._parseDate(p); } var vdate = methods._parseDate(field.val()); if (vdate > pdate) { var rule = options.allrules.past; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks date is in the future * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _future: function(form, field, rules, i, options) { var p = rules[i + 1]; var fieldAlt = $(form.find("input[name='" + p.replace(/^#+/, '') + "']")); var pdate; if (p.toLowerCase() == "now") { pdate = new Date(); } else if (undefined != fieldAlt.val()) { if (fieldAlt.is(":disabled")) return; pdate = methods._parseDate(fieldAlt.val()); } else { pdate = methods._parseDate(p); } var vdate = methods._parseDate(field.val()); if (vdate < pdate) { var rule = options.allrules.future; if (rule.alertText2) return rule.alertText + methods._dateToString(pdate) + rule.alertText2; return rule.alertText + methods._dateToString(pdate); } }, /** * Checks if valid date * * @param {string} date string * @return a bool based on determination of valid date */ _isDate: function(value) { var dateRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/); return dateRegEx.test(value); }, /** * Checks if valid date time * * @param {string} date string * @return a bool based on determination of valid date time */ _isDateTime: function(value) { var dateTimeRegEx = new RegExp(/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/); return dateTimeRegEx.test(value); }, //Checks if the start date is before the end date //returns true if end is later than start _dateCompare: function(start, end) { return (new Date(start.toString()) < new Date(end.toString())); }, /** * Checks date range * * @param {jqObject} first field name * @param {jqObject} second field name * @return an error string if validation failed */ _dateRange: function(field, rules, i, options) { //are not both populated if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are not both dates if (!methods._isDate(options.firstOfGroup[0].value) || !methods._isDate(options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are both dates but range is off if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } }, /** * Checks date time range * * @param {jqObject} first field name * @param {jqObject} second field name * @return an error string if validation failed */ _dateTimeRange: function(field, rules, i, options) { //are not both populated if ((!options.firstOfGroup[0].value && options.secondOfGroup[0].value) || (options.firstOfGroup[0].value && !options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are not both dates if (!methods._isDateTime(options.firstOfGroup[0].value) || !methods._isDateTime(options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } //are both dates but range is off if (!methods._dateCompare(options.firstOfGroup[0].value, options.secondOfGroup[0].value)) { return options.allrules[rules[i]].alertText + options.allrules[rules[i]].alertText2; } }, /** * Max number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _maxCheckbox: function(form, field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = form.find("input[name='" + groupname + "']:checked").size(); if (groupSize > nbCheck) { options.showArrow = false; if (options.allrules.maxCheckbox.alertText2) return options.allrules.maxCheckbox.alertText + " " + nbCheck + " " + options.allrules.maxCheckbox.alertText2; return options.allrules.maxCheckbox.alertText; } }, /** * Min number of checkbox selected * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _minCheckbox: function(form, field, rules, i, options) { var nbCheck = rules[i + 1]; var groupname = field.attr("name"); var groupSize = form.find("input[name='" + groupname + "']:checked").size(); if (groupSize < nbCheck) { options.showArrow = false; return options.allrules.minCheckbox.alertText + " " + nbCheck + " " + options.allrules.minCheckbox.alertText2; } }, /** * Checks that it is a valid credit card number according to the * Luhn checksum algorithm. * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _creditCard: function(field, rules, i, options) { //spaces and dashes may be valid characters, but must be stripped to calculate the checksum. var valid = false, cardNumber = field.val().replace(/ +/g, '').replace(/-+/g, ''); var numDigits = cardNumber.length; if (numDigits >= 14 && numDigits <= 16 && parseInt(cardNumber) > 0) { var sum = 0, i = numDigits - 1, pos = 1, digit, luhn = new String(); do { digit = parseInt(cardNumber.charAt(i)); luhn += (pos++ % 2 == 0) ? digit * 2 : digit; } while (--i >= 0) for (i = 0; i < luhn.length; i++) { sum += parseInt(luhn.charAt(i)); } valid = sum % 10 == 0; } if (!valid) return options.allrules.creditCard.alertText; }, /** * Ajax field validation * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return nothing! the ajax validator handles the prompts itself */ _ajax: function(field, rules, i, options) { var errorSelector = rules[i + 1]; var rule = options.allrules[errorSelector]; var extraData = rule.extraData; var extraDataDynamic = rule.extraDataDynamic; var data = { "fieldId": field.attr("id"), "fieldValue": field.val() }; if (typeof extraData === "object") { $.extend(data, extraData); } else if (typeof extraData === "string") { var tempData = extraData.split("&"); for (var i = 0; i < tempData.length; i++) { var values = tempData[i].split("="); if (values[0] && values[0]) { data[values[0]] = values[1]; } } } if (extraDataDynamic) { var tmpData = []; var domIds = String(extraDataDynamic).split(","); for (var i = 0; i < domIds.length; i++) { var id = domIds[i]; if ($(id).length) { var inputValue = field.closest("form").find(id).val(); var keyValue = id.replace('#', '') + '=' + escape(inputValue); data[id.replace('#', '')] = inputValue; } } } // If a field change event triggered this we want to clear the cache for this ID if (options.eventTrigger == "field") { delete (options.ajaxValidCache[field.attr("id")]); } // If there is an error or if the the field is already validated, do not re-execute AJAX if (!options.isError && !methods._checkAjaxFieldStatus(field.attr("id"), options)) { $.ajax({ type: options.ajaxFormValidationMethod, url: rule.url, cache: false, dataType: "json", data: data, field: field, rule: rule, methods: methods, options: options, beforeSend: function() { }, error: function(data, transport) { methods._ajaxError(data, transport); }, success: function(json) { // asynchronously called on success, data is the json answer from the server var errorFieldId = json[0]; //var errorField = $($("#" + errorFieldId)[0]); var errorField = $("#" + errorFieldId + "']").eq(0); // make sure we found the element if (errorField.length == 1) { var status = json[1]; // read the optional msg from the server var msg = json[2]; if (!status) { // Houston we got a problem - display an red prompt options.ajaxValidCache[errorFieldId] = false; options.isError = true; // resolve the msg prompt if (msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertText; if (txt) { msg = txt; } } } else msg = rule.alertText; methods._showPrompt(errorField, msg, "", true, options); } else { options.ajaxValidCache[errorFieldId] = true; // resolves the msg prompt if (msg) { if (options.allrules[msg]) { var txt = options.allrules[msg].alertTextOk; if (txt) { msg = txt; } } } else msg = rule.alertTextOk; // see if we should display a green prompt if (msg) methods._showPrompt(errorField, msg, "pass", true, options); else methods._closePrompt(errorField); // If a submit form triggered this, we want to re-submit the form if (options.eventTrigger == "submit") field.closest("form").submit(); } } errorField.trigger("jqv.field.result", [errorField, options.isError, msg]); } }); return rule.alertTextLoad; } }, /** * Common method to handle ajax errors * * @param {Object} data * @param {Object} transport */ _ajaxError: function(data, transport) { if (data.status == 0 && transport == null) alert("The page is not served from a server! ajax call failed"); else if (typeof console != "undefined") console.log("Ajax error: " + data.status + " " + transport); }, /** * date -> string * * @param {Object} date */ _dateToString: function(date) { return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); }, /** * Parses an ISO date * @param {String} d */ _parseDate: function(d) { var dateParts = d.split("-"); if (dateParts == d) dateParts = d.split("/"); return new Date(dateParts[0], (dateParts[1] - 1), dateParts[2]); }, /** * Builds or updates a prompt with the given information * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _showPrompt: function(field, promptText, type, ajaxed, options, ajaxform) { var prompt = methods._getPrompt(field); // The ajax submit errors are not see has an error in the form, // When the form errors are returned, the engine see 2 bubbles, but those are ebing closed by the engine at the same time // Because no error was found befor submitting if (ajaxform) prompt = false; if (prompt) methods._updatePrompt(field, prompt, promptText, type, ajaxed, options); else methods._buildPrompt(field, promptText, type, ajaxed, options); }, /** * Builds and shades a prompt for the given field. * * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _buildPrompt: function(field, promptText, type, ajaxed, options) { // create the prompt var prompt = $('<div>'); prompt.addClass(methods._getClassName(field.attr("id")) + "formError"); // add a class name to identify the parent form of the prompt prompt.addClass("parentForm" + methods._getClassName(field.parents('form').attr("id"))); prompt.addClass("formError"); switch (type) { case "pass": prompt.addClass("greenPopup"); break; case "load": prompt.addClass("blackPopup"); break; default: /* it has error */ //alert("unknown popup type:"+type); } if (ajaxed) prompt.addClass("ajaxed"); // create the prompt content var promptContent = $('<div>').addClass("formErrorContent").html(promptText).appendTo(prompt); // create the css arrow pointing at the field // note that there is no triangle on max-checkbox and radio if (options.showArrow) { var arrow = $('<div>').addClass("formErrorArrow"); //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10) var positionType = field.data("promptPosition") || options.promptPosition; if (typeof (positionType) == 'string') { var pos = positionType.indexOf(":"); if (pos != -1) positionType = positionType.substring(0, pos); } switch (positionType) { case "bottomLeft": case "bottomRight": prompt.find(".formErrorContent").before(arrow); arrow.addClass("formErrorArrowBottom").html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>'); break; case "topLeft": case "topRight": arrow.html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>'); prompt.append(arrow); break; } } // Modify z-indexes for jquery ui if (field.closest('.ui-dialog').length) prompt.addClass('formErrorInsideDialog'); prompt.css({ "opacity": 0, 'position': 'absolute' }); field.before(prompt); var pos = methods._calculatePosition(field, prompt, options); prompt.css({ "top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize, "opacity": 0 }).data("callerField", field); if (options.autoHidePrompt) { setTimeout(function() { prompt.animate({ "opacity": 0 }, function() { prompt.closest('.formErrorOuter').remove(); prompt.remove(); }); }, options.autoHideDelay); } return prompt.animate({ "opacity": 0.87 }); }, /** * Updates the prompt text field - the field for which the prompt * @param {jqObject} field * @param {String} promptText html text to display type * @param {String} type the type of bubble: 'pass' (green), 'load' (black) anything else (red) * @param {boolean} ajaxed - use to mark fields than being validated with ajax * @param {Map} options user options */ _updatePrompt: function(field, prompt, promptText, type, ajaxed, options, noAnimation) { if (prompt) { if (typeof type !== "undefined") { if (type == "pass") prompt.addClass("greenPopup"); else prompt.removeClass("greenPopup"); if (type == "load") prompt.addClass("blackPopup"); else prompt.removeClass("blackPopup"); } if (ajaxed) prompt.addClass("ajaxed"); else prompt.removeClass("ajaxed"); prompt.find(".formErrorContent").html(promptText); var pos = methods._calculatePosition(field, prompt, options); var css = { "top": pos.callerTopPosition, "left": pos.callerleftPosition, "marginTop": pos.marginTopSize }; if (noAnimation) prompt.css(css); else prompt.animate(css); } }, /** * Closes the prompt associated with the given field * * @param {jqObject} * field */ _closePrompt: function(field) { var prompt = methods._getPrompt(field); if (prompt) prompt.fadeTo("fast", 0, function() { prompt.parent('.formErrorOuter').remove(); prompt.remove(); }); }, closePrompt: function(field) { return methods._closePrompt(field); }, /** * Returns the error prompt matching the field if any * * @param {jqObject} * field * @return undefined or the error prompt (jqObject) */ _getPrompt: function(field) { var formId = $(field).closest('form').attr('id'); var className = methods._getClassName(field.attr("id")) + "formError"; var match = $("." + methods._escapeExpression(className) + '.parentForm' + formId)[0]; if (match) return $(match); }, /** * Returns the escapade classname * * @param {selector} * className */ _escapeExpression: function(selector) { return selector.replace(/([#;&,\.\+\*\~':"\!\^$\[\]\(\)=>\|])/g, "\\$1"); }, /** * returns true if we are in a RTLed document * * @param {jqObject} field */ isRTL: function(field) { var $document = $(document); var $body = $('body'); var rtl = (field && field.hasClass('rtl')) || (field && (field.attr('dir') || '').toLowerCase() === 'rtl') || $document.hasClass('rtl') || ($document.attr('dir') || '').toLowerCase() === 'rtl' || $body.hasClass('rtl') || ($body.attr('dir') || '').toLowerCase() === 'rtl'; return Boolean(rtl); }, /** * Calculates prompt position * * @param {jqObject} * field * @param {jqObject} * the prompt * @param {Map} * options * @return positions */ _calculatePosition: function(field, promptElmt, options) { var promptTopPosition, promptleftPosition, marginTopSize; var fieldWidth = field.width(); var fieldLeft = field.position().left; var fieldTop = field.position().top; var fieldHeight = field.height(); var promptHeight = promptElmt.height(); // is the form contained in an overflown container? promptTopPosition = promptleftPosition = 0; // compensation for the arrow marginTopSize = -promptHeight; //prompt positioning adjustment support //now you can adjust prompt position //usage: positionType:Xshift,Yshift //for example: // bottomLeft:+20 means bottomLeft position shifted by 20 pixels right horizontally // topRight:20, -15 means topRight position shifted by 20 pixels to right and 15 pixels to top //You can use +pixels, - pixels. If no sign is provided than + is default. var positionType = field.data("promptPosition") || options.promptPosition; var shift1 = ""; var shift2 = ""; var shiftX = 0; var shiftY = 0; if (typeof (positionType) == 'string') { //do we have any position adjustments ? if (positionType.indexOf(":") != -1) { shift1 = positionType.substring(positionType.indexOf(":") + 1); positionType = positionType.substring(0, positionType.indexOf(":")); //if any advanced positioning will be needed (percents or something else) - parser should be added here //for now we use simple parseInt() //do we have second parameter? if (shift1.indexOf(",") != -1) { shift2 = shift1.substring(shift1.indexOf(",") + 1); shift1 = shift1.substring(0, shift1.indexOf(",")); shiftY = parseInt(shift2); if (isNaN(shiftY)) shiftY = 0; }; shiftX = parseInt(shift1); if (isNaN(shift1)) shift1 = 0; }; }; switch (positionType) { default: case "topRight": promptleftPosition += fieldLeft + fieldWidth - 30; promptTopPosition += fieldTop; break; case "topLeft": promptTopPosition += fieldTop; promptleftPosition += fieldLeft; break; case "centerRight": promptTopPosition = fieldTop + 4; marginTopSize = 0; promptleftPosition = fieldLeft + field.outerWidth(true) + 5; break; case "centerLeft": promptleftPosition = fieldLeft - (promptElmt.width() + 2); promptTopPosition = fieldTop + 4; marginTopSize = 0; break; case "bottomLeft": promptTopPosition = fieldTop + field.height() + 5; marginTopSize = 0; promptleftPosition = fieldLeft; break; case "bottomRight": promptleftPosition = fieldLeft + fieldWidth - 30; promptTopPosition = fieldTop + field.height() + 5; marginTopSize = 0; }; //apply adjusments if any promptleftPosition += shiftX; promptTopPosition += shiftY; return { "callerTopPosition": promptTopPosition + "px", "callerleftPosition": promptleftPosition + "px", "marginTopSize": marginTopSize + "px" }; }, /** * Saves the user options and variables in the form.data * * @param {jqObject} * form - the form where the user option should be saved * @param {Map} * options - the user options * @return the user options (extended from the defaults) */ _saveOptions: function(form, options) { // is there a language localisation ? if ($.validationEngineLanguage) var allRules = $.validationEngineLanguage.allRules; else $.error("jQuery.validationEngine rules are not loaded, plz add localization files to the page"); // --- Internals DO NOT TOUCH or OVERLOAD --- // validation rules and i18 $.validationEngine.defaults.allrules = allRules; var userOptions = $.extend(true, {}, $.validationEngine.defaults, options); form.data('jqv', userOptions); return userOptions; }, /** * Removes forbidden characters from class name * @param {String} className */ _getClassName: function(className) { if (className) return className.replace(/:/g, "_").replace(/\./g, "_"); }, /** * Escape special character for jQuery selector * http://totaldev.com/content/escaping-characters-get-valid-jquery-id * @param {String} selector */ _jqSelector: function(str) { return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); }, /** * Conditionally required field * * @param {jqObject} field * @param {Array[String]} rules * @param {int} i rules index * @param {Map} * user options * @return an error string if validation failed */ _condRequired: function(field, rules, i, options) { var idx, dependingField; for (idx = (i + 1); idx < rules.length; idx++) { dependingField = jQuery("#" + rules[idx]).first(); /* Use _required for determining wether dependingField has a value. * There is logic there for handling all field types, and default value; so we won't replicate that here */ if (dependingField.length && methods._required(dependingField, ["required"], 0, options) == undefined) { /* We now know any of the depending fields has a value, * so we can validate this field as per normal required code */ return methods._required(field, ["required"], 0, options); } } } }; /** * Plugin entry point. * You may pass an action as a parameter or a list of options. * if none, the init and attach methods are being called. * Remember: if you pass options, the attached method is NOT called automatically * * @param {String} * method (optional) action */ $.fn.validationEngine = function(method) { var form = $(this); if (!form[0]) return form; // stop here if the form does not exist if (typeof (method) == 'string' && method.charAt(0) != '_' && methods[method]) { // make sure init is called once if (method != "showPrompt" && method != "hide" && method != "hideAll") methods.init.apply(form); return methods[method].apply(form, Array.prototype.slice.call(arguments, 1)); } else if (typeof method == 'object' || !method) { // default constructor with or without arguments methods.init.apply(form, arguments); return methods.attach.apply(form); } else { $.error('Method ' + method + ' does not exist in jQuery.validationEngine'); } }; // LEAK GLOBAL OPTIONS $.validationEngine = { fieldIdCounter: 0, defaults: { // Name of the event triggering field validation validationEventTrigger: "blur", // Automatically scroll viewport to the first error scroll: true, // Focus on the first input focusFirstField: true, // Opening box position, possible locations are: topLeft, // topRight, bottomLeft, centerRight, bottomRight promptPosition: "topRight", bindMethod: "bind", // internal, automatically set to true when it parse a _ajax rule inlineAjax: false, // if set to true, the form data is sent asynchronously via ajax to the form.action url (get) ajaxFormValidation: false, // The url to send the submit ajax validation (default to action) ajaxFormValidationURL: false, // HTTP method used for ajax validation ajaxFormValidationMethod: 'get', // Ajax form validation callback method: boolean onComplete(form, status, errors, options) // retuns false if the form.submit event needs to be canceled. onAjaxFormComplete: $.noop, // called right before the ajax call, may return false to cancel onBeforeAjaxFormValidation: $.noop, // Stops form from submitting and execute function assiciated with it onValidationComplete: false, // Used when you have a form fields too close and the errors messages are on top of other disturbing viewing messages doNotShowAllErrosOnSubmit: false, // Object where you store custom messages to override the default error messages custom_error_messages: {}, // true if you want to vind the input fields binded: true, // set to true, when the prompt arrow needs to be displayed showArrow: true, // did one of the validation fail ? kept global to stop further ajax validations isError: false, // Limit how many displayed errors a field can have maxErrorsPerField: false, // Caches field validation status, typically only bad status are created. // the array is used during ajax form validation to detect issues early and prevent an expensive submit ajaxValidCache: {}, // Auto update prompt position after window resize autoPositionUpdate: false, InvalidFields: [], onFieldSuccess: false, onFieldFailure: false, onFormSuccess: false, onFormFailure: false, addSuccessCssClassToField: false, addFailureCssClassToField: false, // Auto-hide prompt autoHidePrompt: false, // Delay before auto-hide autoHideDelay: 10000, // Fade out duration while hiding the validations fadeDuration: 0.3, // Use Prettify select library prettySelect: false, // Custom ID uses prefix usePrefix: "", // Custom ID uses suffix useSuffix: "", // Only show one message per error prompt showOneMessage: false } }; $(function() { $.validationEngine.defaults.promptPosition = methods.isRTL() ? 'topLeft' : "topRight" }); })(jQuery);
JavaScript
(function($){ $.fn.validationEngineLanguage = function(){ }; $.validationEngineLanguage = { newLang: function(){ $.validationEngineLanguage.allRules = { "required": { // Add your regex rules here, you can take telephone as an example "regex": "none", "alertText": "* This field is required", "alertTextCheckboxMultiple": "* Please select an option", "alertTextCheckboxe": "* This checkbox is required", "alertTextDateRange": "* Both date range fields are required" }, "requiredInFunction": { "func": function(field, rules, i, options){ return (field.val() == "test") ? true : false; }, "alertText": "* Field must equal test" }, "dateRange": { "regex": "none", "alertText": "* Invalid ", "alertText2": "Date Range" }, "dateTimeRange": { "regex": "none", "alertText": "* Invalid ", "alertText2": "Date Time Range" }, "minSize": { "regex": "none", "alertText": "* Minimum ", "alertText2": " characters required" }, "maxSize": { "regex": "none", "alertText": "* Maximum ", "alertText2": " characters allowed" }, "groupRequired": { "regex": "none", "alertText": "* You must fill one of the following fields" }, "min": { "regex": "none", "alertText": "* Minimum value is " }, "max": { "regex": "none", "alertText": "* Maximum value is " }, "past": { "regex": "none", "alertText": "* Date prior to " }, "future": { "regex": "none", "alertText": "* Date past " }, "maxCheckbox": { "regex": "none", "alertText": "* Maximum ", "alertText2": " options allowed" }, "minCheckbox": { "regex": "none", "alertText": "* Please select ", "alertText2": " options" }, "equals": { "regex": "none", "alertText": "* Fields do not match" }, "creditCard": { "regex": "none", "alertText": "* Invalid credit card number" }, "phone": { // credit: jquery.h5validate.js / orefalo "regex": /^([\+][0-9]{1,3}[\ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9\ \.\-\/]{3,20})((x|ext|extension)[\ ]?[0-9]{1,4})?$/, "alertText": "* Invalid phone number" }, "email": { // HTML5 compatible email regex ( http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html# e-mail-state-%28type=email%29 ) "regex": /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, "alertText": "* Invalid email address" }, "integer": { "regex": /^[\-\+]?\d+$/, "alertText": "* Not a valid integer" }, "number": { // Number, including positive, negative, and floating decimal. credit: orefalo "regex": /^[\-\+]?((([0-9]{1,3})([,][0-9]{3})*)|([0-9]+))?([\.]([0-9]+))?$/, "alertText": "* Invalid floating decimal number" }, "date": { // Check if date is valid by leap year "func": function (field) { var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/); var match = pattern.exec(field.val()); if (match == null) return false; var year = match[1]; var month = match[2]*1; var day = match[3]*1; var date = new Date(year, month - 1, day); // because months starts from 0. return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day); }, "alertText": "* Invalid date, must be in YYYY-MM-DD format" }, "ipv4": { "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/, "alertText": "* Invalid IP address" }, "url": { "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i, "alertText": "* Invalid URL" }, "onlyNumberSp": { "regex": /^[0-9\ ]+$/, "alertText": "* Numbers only" }, "onlyLetterSp": { "regex": /^[a-zA-Z\ \']+$/, "alertText": "* Letters only" }, "onlyLetterNumber": { "regex": /^[0-9a-zA-Z]+$/, "alertText": "* No special characters allowed" }, // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings "ajaxUserCall": { "url": "ajaxValidateFieldUser", // you may want to pass extra data on the ajax call "extraData": "name=eric", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxUserCallPhp": { "url": "phpajax/ajaxValidateFieldUser.php", // you may want to pass extra data on the ajax call "extraData": "name=eric", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This username is available", "alertText": "* This user is already taken", "alertTextLoad": "* Validating, please wait" }, "ajaxNameCall": { // remote json service location "url": "ajaxValidateFieldName", // error "alertText": "* This name is already taken", // if you provide an "alertTextOk", it will show as a green prompt when the field validates "alertTextOk": "* This name is available", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "ajaxNameCallPhp": { // remote json service location "url": "phpajax/ajaxValidateFieldName.php", // error "alertText": "* This name is already taken", // speaks by itself "alertTextLoad": "* Validating, please wait" }, "validate2fields": { "alertText": "* Please input HELLO" }, //tls warning:homegrown not fielded "dateFormat":{ "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/, "alertText": "* Invalid Date" }, //tls warning:homegrown not fielded "dateTimeFormat": { "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1}$|^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^((1[012]|0?[1-9]){1}\/(0?[1-9]|[12][0-9]|3[01]){1}\/\d{2,4}\s+(1[012]|0?[1-9]){1}:(0?[1-5]|[0-6][0-9]){1}:(0?[0-6]|[0-6][0-9]){1}\s+(am|pm|AM|PM){1})$/, "alertText": "* Invalid Date or Date Format", "alertText2": "Expected Format: ", "alertText3": "mm/dd/yyyy hh:mm:ss AM|PM or ", "alertText4": "yyyy-mm-dd hh:mm:ss AM|PM" } }; } }; $.validationEngineLanguage.newLang(); })(jQuery);
JavaScript
$(document).ready(function() { // Our Confirm method function Confirm(question, callback) { // Content will consist of the question and ok/cancel buttons var message = $('<p />', { text: question }), ok = $('<button />', { text: 'Ok', click: function() { callback(true); } }), cancel = $('<button />', { text: 'Cancel', click: function() { callback(false); } }); dialogue(message.add(ok).add(cancel), 'Do you agree?'); } // Our Alert method function Alert(message) { // Content will consist of the message and an ok button var message = $('<p />', { text: message }), ok = $('<button />', { text: 'Ok', 'class': 'full' }); dialogue(message.add(ok), 'Alert!'); } // Our Prompt method function Prompt(question, initial, callback) { // Content will consist of a question elem and input, with ok/cancel buttons var message = $('<p />', { text: question }), input = $('<input />', { val: initial }), ok = $('<button />', { text: 'Ok', click: function() { callback(input.val()); } }), cancel = $('<button />', { text: 'Cancel', click: function() { callback(null); } }); dialogue(message.add(input).add(ok).add(cancel), 'Attention!'); } function dialogue(content, title) { /* * Since the dialogue isn't really a tooltip as such, we'll use a dummy * out-of-DOM element as our target instead of an actual element like document.body */ $('<div />').qtip( { content: { text: content, title: title }, position: { my: 'center', at: 'center', // Center it... target: $(window) // ... in the window }, show: { ready: true, // Show it straight away modal: { on: true, // Make it modal (darken the rest of the page)... blur: false // ... but don't close the tooltip when clicked } }, hide: false, // We'll hide it maunally so disable hide events style: 'qtip-light qtip-rounded qtip-dialogue', // Add a few styles events: { // Hide the tooltip when any buttons in the dialogue are clicked render: function(event, api) { $('button', api.elements.content).click(api.hide); }, // Destroy the tooltip once it's hidden as we no longer need it! hide: function(event, api) { api.destroy(); } } }); } //Checked $('#toggle-all-pending').click(function() { // if ($(this).attr('class') != "toggle-checked") { $('#mainformpending input[type=checkbox]').attr('checked', false); } $('#mainformpending input').checkBox(); $('#toggle-all-pending').toggleClass('toggle-checked'); $('#mainformpending input[type=checkbox]').checkBox('toggle'); return false; }); $('#mainformpending input:checkbox:not(#toggle-all-pending)').click(function() { $('#toggle-all-pending').removeClass('toggle-checked'); }); //Checked $('#toggle-all-rejected').click(function() { // if ($(this).attr('class') != "toggle-checked") { $('#mainformrejected input[type=checkbox]').attr('checked', false); } $('#mainformrejected input').checkBox(); $('#toggle-all-rejected').toggleClass('toggle-checked'); $('#mainformrejected input[type=checkbox]').checkBox('toggle'); return false; }); $('#mainformrejected input:checkbox:not(#toggle-all-rejected)').click(function() { $('#toggle-all-rejected').removeClass('toggle-checked'); }); // //prompt for delete button $('.remove-btn').click(function(e) { e.preventDefault(); //prevent default action for anchor var self = this; Confirm("Confirm removed the selected records?", function(yes) { if (yes) { window.location = self.href; } }); }); //bulk process action $('.action-invoke').click(function(e) { e.preventDefault(); //prevent default action for anchor //ensure at least one item is checked var fields = $("input[name='selected']").serializeArray(); if (fields.length == 0) { Alert('Please select at least one item.'); return false; } else { //submit form $(".list_item_form").attr("action", this.href); $(".list_item_form").submit(); } }); //bulk process delete action $('.action-invoke-removed').click(function(e) { e.preventDefault(); //prevent default action for anchor //ensure at least one item is checked var fields = $("input[name='selected']").serializeArray(); if (fields.length == 0) { Alert('Please select at least one item.'); return false; } else { var self = this; Confirm("Confirm removed the selected records?", function(yes) { if (yes) { $(".list_item_form").attr("action", self.href); $(".list_item_form").submit(); } }); } }); // 1 - START DROPDOWN SLIDER SCRIPTS ------------------------------------------------------------------------ $(".action-slider").click(function() { $("#actions-box-slider").slideToggle("fast"); $(this).toggleClass("activated"); return false; }); $(".action-slider-reject").click(function() { $("#actions-box-slider-reject").slideToggle("fast"); $(this).toggleClass("activated"); return false; }); // END ----------------------------- 1 });
JavaScript
/*! * Media helper for fancyBox * version: 1.0.5 (Tue, 23 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * media: true * } * }); * * Set custom URL parameters: * $(".fancybox").fancybox({ * helpers : { * media: { * youtube : { * params : { * autoplay : 0 * } * } * } * } * }); * * Or: * $(".fancybox").fancybox({, * helpers : { * media: true * }, * youtube : { * autoplay: 0 * } * }); * * Supports: * * Youtube * http://www.youtube.com/watch?v=opj24KnzrWo * http://www.youtube.com/embed/opj24KnzrWo * http://youtu.be/opj24KnzrWo * Vimeo * http://vimeo.com/40648169 * http://vimeo.com/channels/staffpicks/38843628 * http://vimeo.com/groups/surrealism/videos/36516384 * http://player.vimeo.com/video/45074303 * Metacafe * http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/ * http://www.metacafe.com/watch/7635964/ * Dailymotion * http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people * Twitvid * http://twitvid.com/QY7MD * Twitpic * http://twitpic.com/7p93st * Instagram * http://instagr.am/p/IejkuUGxQn/ * http://instagram.com/p/IejkuUGxQn/ * Google maps * http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17 * http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16 * http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56 */ (function ($) { "use strict"; //Shortcut for fancyBox object var F = $.fancybox, format = function( url, rez, params ) { params = params || ''; if ( $.type( params ) === "object" ) { params = $.param(params, true); } $.each(rez, function(key, value) { url = url.replace( '$' + key, value || '' ); }); if (params.length) { url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params; } return url; }; //Add helper object F.helpers.media = { defaults : { youtube : { matcher : /(youtube\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i, params : { autoplay : 1, autohide : 1, fs : 1, rel : 0, hd : 1, wmode : 'opaque', enablejsapi : 1 }, type : 'iframe', url : '//www.youtube.com/embed/$3' }, vimeo : { matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/, params : { autoplay : 1, hd : 1, show_title : 1, show_byline : 1, show_portrait : 0, fullscreen : 1 }, type : 'iframe', url : '//player.vimeo.com/video/$1' }, metacafe : { matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/, params : { autoPlay : 'yes' }, type : 'swf', url : function( rez, params, obj ) { obj.swf.flashVars = 'playerVars=' + $.param( params, true ); return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf'; } }, dailymotion : { matcher : /dailymotion.com\/video\/(.*)\/?(.*)/, params : { additionalInfos : 0, autoStart : 1 }, type : 'swf', url : '//www.dailymotion.com/swf/video/$1' }, twitvid : { matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i, params : { autoplay : 0 }, type : 'iframe', url : '//www.twitvid.com/embed.php?guid=$1' }, twitpic : { matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i, type : 'image', url : '//twitpic.com/show/full/$1/' }, instagram : { matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i, type : 'image', url : '//$1/p/$2/media/' }, google_maps : { matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i, type : 'iframe', url : function( rez ) { return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed'); } } }, beforeLoad : function(opts, obj) { var url = obj.href || '', type = false, what, item, rez, params; for (what in opts) { item = opts[ what ]; rez = url.match( item.matcher ); if (rez) { type = item.type; params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null)); url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params ); break; } } if (type) { obj.href = url; obj.type = type; obj.autoHeight = false; } } }; }(jQuery));
JavaScript
/*! * Buttons helper for fancyBox * version: 1.0.5 (Mon, 15 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * buttons: { * position : 'top' * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.buttons = { defaults : { skipSingle : false, // disables if gallery contains single image position : 'top', // 'top' or 'bottom' tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:jQuery.fancybox.close();"></a></li></ul></div>' }, list : null, buttons: null, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (opts.skipSingle && obj.group.length < 2) { obj.helpers.buttons = false; obj.closeBtn = true; return; } //Increase top margin to give space for buttons obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30; }, onPlayStart: function () { if (this.buttons) { this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn'); } }, onPlayEnd: function () { if (this.buttons) { this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn'); } }, afterShow: function (opts, obj) { var buttons = this.buttons; if (!buttons) { this.list = $(opts.tpl).addClass(opts.position).appendTo('body'); buttons = { prev : this.list.find('.btnPrev').click( F.prev ), next : this.list.find('.btnNext').click( F.next ), play : this.list.find('.btnPlay').click( F.play ), toggle : this.list.find('.btnToggle').click( F.toggle ) } } //Prev if (obj.index > 0 || obj.loop) { buttons.prev.removeClass('btnDisabled'); } else { buttons.prev.addClass('btnDisabled'); } //Next / Play if (obj.loop || obj.index < obj.group.length - 1) { buttons.next.removeClass('btnDisabled'); buttons.play.removeClass('btnDisabled'); } else { buttons.next.addClass('btnDisabled'); buttons.play.addClass('btnDisabled'); } this.buttons = buttons; this.onUpdate(opts, obj); }, onUpdate: function (opts, obj) { var toggle; if (!this.buttons) { return; } toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn'); //Size toggle button if (obj.canShrink) { toggle.addClass('btnToggleOn'); } else if (!obj.canExpand) { toggle.addClass('btnDisabled'); } }, beforeClose: function () { if (this.list) { this.list.remove(); } this.list = null; this.buttons = null; } }; }(jQuery));
JavaScript
/*! * Thumbnail helper for fancyBox * version: 1.0.7 (Mon, 01 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * thumbs: { * width : 50, * height : 50 * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.thumbs = { defaults : { width : 50, // thumbnail width height : 50, // thumbnail height position : 'bottom', // 'top' or 'bottom' source : function ( item ) { // function to obtain the URL of the thumbnail image var href; if (item.element) { href = $(item.element).find('img').attr('src'); } if (!href && item.type === 'image' && item.href) { href = item.href; } return href; } }, wrap : null, list : null, width : 0, init: function (opts, obj) { var that = this, list, thumbWidth = opts.width, thumbHeight = opts.height, thumbSource = opts.source; //Build list structure list = ''; for (var n = 0; n < obj.group.length; n++) { list += '<li><a style="width:' + thumbWidth + 'px;height:' + thumbHeight + 'px;" href="javascript:jQuery.fancybox.jumpto(' + n + ');"></a></li>'; } this.wrap = $('<div id="fancybox-thumbs"></div>').addClass(opts.position).appendTo('body'); this.list = $('<ul>' + list + '</ul>').appendTo(this.wrap); //Load each thumbnail $.each(obj.group, function (i) { var href = thumbSource( obj.group[ i ] ); if (!href) { return; } $("<img />").load(function () { var width = this.width, height = this.height, widthRatio, heightRatio, parent; if (!that.list || !width || !height) { return; } //Calculate thumbnail width/height and center it widthRatio = width / thumbWidth; heightRatio = height / thumbHeight; parent = that.list.children().eq(i).find('a'); if (widthRatio >= 1 && heightRatio >= 1) { if (widthRatio > heightRatio) { width = Math.floor(width / heightRatio); height = thumbHeight; } else { width = thumbWidth; height = Math.floor(height / widthRatio); } } $(this).css({ width : width, height : height, top : Math.floor(thumbHeight / 2 - height / 2), left : Math.floor(thumbWidth / 2 - width / 2) }); parent.width(thumbWidth).height(thumbHeight); $(this).hide().appendTo(parent).fadeIn(300); }).attr('src', href); }); //Set initial width this.width = this.list.children().eq(0).outerWidth(true); this.list.width(this.width * (obj.group.length + 1)).css('left', Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5))); }, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (obj.group.length < 2) { obj.helpers.thumbs = false; return; } //Increase bottom margin to give space for thumbs obj.margin[ opts.position === 'top' ? 0 : 2 ] += ((opts.height) + 15); }, afterShow: function (opts, obj) { //Check if exists and create or update list if (this.list) { this.onUpdate(opts, obj); } else { this.init(opts, obj); } //Set active element this.list.children().removeClass('active').eq(obj.index).addClass('active'); }, //Center list onUpdate: function (opts, obj) { if (this.list) { this.list.stop(true).animate({ 'left': Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5)) }, 150); } }, beforeClose: function () { if (this.wrap) { this.wrap.remove(); } this.wrap = null; this.list = null; this.width = 0; } } }(jQuery));
JavaScript
$(document).ready(function() { // Our Confirm method function Confirm(question, callback) { // Content will consist of the question and ok/cancel buttons var message = $('<p />', { text: question }), cancel = $('<button />', { text: 'Yes', click: function() { callback(true); } }), ok = $('<button />', { text: 'No', click: function() { callback(false); } }) ; dialogue(message.add(ok).add(cancel), 'Confirm'); } // Our Alert method function Alert(message) { // Content will consist of the message and an ok button var message = $('<p />', { text: message }), ok = $('<button />', { text: 'Ok', 'class': 'full' }); dialogue(message.add(ok), 'Alert!'); } // Our Prompt method function Prompt(question, initial, callback) { // Content will consist of a question elem and input, with ok/cancel buttons var message = $('<p />', { text: question }), input = $('<input />', { val: initial }), ok = $('<button />', { text: 'Ok', click: function() { callback(input.val()); } }), cancel = $('<button />', { text: 'Cancel', click: function() { callback(null); } }); dialogue(message.add(input).add(ok).add(cancel), 'Attention!'); } function dialogue(content, title) { /* * Since the dialogue isn't really a tooltip as such, we'll use a dummy * out-of-DOM element as our target instead of an actual element like document.body */ $('<div />').qtip( { content: { text: content, title: title }, position: { my: 'center', at: 'center', // Center it... target: $(window) // ... in the window }, show: { ready: true, // Show it straight away modal: { on: true, // Make it modal (darken the rest of the page)... blur: false // ... but don't close the tooltip when clicked } }, hide: false, // We'll hide it maunally so disable hide events style: 'qtip-light qtip-rounded qtip-dialogue', // Add a few styles events: { // Hide the tooltip when any buttons in the dialogue are clicked render: function(event, api) { $('button', api.elements.content).click(api.hide); }, // Destroy the tooltip once it's hidden as we no longer need it! hide: function(event, api) { api.destroy(); } } }); } //Checked $('#toggle-all').click(function() { // if ($(this).attr('class') != "toggle-checked") { $('#mainform input[type=checkbox]').attr('checked', false); } //alert($(this).attr('class')); $('#mainform input').checkBox(); $('#toggle-all').toggleClass('toggle-checked'); $('#mainform input[type=checkbox]').checkBox('toggle'); return false; }); $('#mainform input:checkbox:not(#toggle-all)').click(function() { $('#toggle-all').removeClass('toggle-checked'); }); //prompt for delete button $('.remove-btn').click(function(e) { e.preventDefault(); //prevent default action for anchor var self = this; Confirm("Confirm removed the selected records?", function(yes) { if (yes) { $("#content-outer").showLoading(); window.location = self.href; } }); }); //bulk process action $('.action-invoke').click(function(e) { e.preventDefault(); //prevent default action for anchor //ensure at least one item is checked var fields = $("input[name='selected']").serializeArray(); if (fields.length == 0) { Alert('Please select at least one item.'); return false; } else { $("#content-outer").showLoading(); //submit form $(".list_item_form").attr("action", this.href); $(".list_item_form").submit(); } }); //bulk process delete action $('.action-invoke-removed').click(function(e) { e.preventDefault(); //prevent default action for anchor //ensure at least one item is checked var fields = $("input[name='selected']").serializeArray(); if (fields.length == 0) { Alert('Please select at least one item.'); return false; } else { var self = this; Confirm("Confirm removed the selected records?", function(yes) { if (yes) { $("#content-outer").showLoading(); $(".list_item_form").attr("action", self.href); $(".list_item_form").submit(); } }); } }); // 1 - START DROPDOWN SLIDER SCRIPTS ------------------------------------------------------------------------ $(".action-slider").click(function() { $("#actions-box-slider").slideToggle("fast"); $(this).toggleClass("activated"); return false; }); $('a[title]').qtip(); // END ----------------------------- 1 });
JavaScript
/********************************************************************************/ // <copyright file="Utility.js" company="Asia E-Business Solutions"> // Copyright © 2012. All right reserved // </copyright> // // <history> // <change who="Hieu Nguyen" date="20/12/2012 2:53:02 PM">Created</change> // <history> /********************************************************************************/ /** * Create Namespace Object **/ var Namespace = { Register: function(_Name) { var chk = false; var cob = ""; var spc = _Name.split("."); for (var i = 0; i < spc.length; i++) { if (cob != "") { cob += "." } cob += spc[i]; chk = this.Exists(cob); if (!chk) { this.Create(cob); } } if (chk) { throw "Namespace: " + _Name + " is already defined."; } }, Create: function(_Src) { eval("window." + _Src + " = new Object(); "); }, Exists: function(_Src) { eval("var NE = false;try{if(" + _Src + "){NE = true;}else{ NE = false;}} catch(err){}"); return NE; } } /** * Dump Object **/ var dump_js = function(variable, maxDeep) { var deep = 0; var maxDeep = maxDeep || 0; function fetch(object, parent) { var buffer = ''; deep++; for (var i in object) { if (parent) { objectPath = parent + '.' + i; } else { objectPath = i; } buffer += objectPath + ' (' + typeof object[i] + ')'; if (typeof object[i] == 'object') { buffer += "\n"; if (deep < maxDeep) { buffer += fetch(object[i], objectPath); } } else if (typeof object[i] == 'function') { buffer += "\n"; } else if (typeof object[i] == 'string') { buffer += ': "' + object[i] + "\"\n"; } else { buffer += ': ' + object[i] + "\n"; } } deep--; return buffer; } if (typeof variable == 'object') { return fetch(variable); } return '(' + typeof variable + '): ' + variable + "-"; } /** *Load Dynamic Css **/ function loadcssfile(filename) { var fileref = document.createElement("link") fileref.setAttribute("rel", "stylesheet") fileref.setAttribute("type", "text/css") fileref.setAttribute("href", filename) if (typeof fileref != "undefined") document.getElementsByTagName("head")[0].appendChild(fileref) } function openWindow(website) { var winwidth = window.screen.availWidth; var winheight = window.screen.availHeight; var windowprops = 'width=' + winwidth + ',height=' + winheight + ',scrollbars=yes,status=yes,resizable=yes,' var left = 0; var top = 0; if (window.resizeTo && navigator.userAgent.indexOf("Opera") == -1) { var sizer = window.open("", "", "left=" + left + ",top=" + top + "," + windowprops); sizer.location = website; } else window.open(website, 'mywindow'); }
JavaScript
/* * jQuery EasIng v1.1.2 - http://gsgd.co.uk/sandbox/jquery.easIng.php * * Uses the built In easIng capabilities added In jQuery 1.1 * to offer multiple easIng options * * Copyright (c) 2007 George Smith * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.extend( jQuery.easing, { easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } });
JavaScript
/** * jQuery Geocoding and Places Autocomplete Plugin - V 1.4 * * @author Martin Kleppe <kleppe@ubilabs.net>, 2012 * @author Ubilabs http://ubilabs.net, 2012 * @license MIT License <http://www.opensource.org/licenses/mit-license.php> */ // # $.geocomplete() // ## jQuery Geocoding and Places Autocomplete Plugin - V 1.4 // // * https://github.com/ubilabs/geocomplete/ // * by Martin Kleppe <kleppe@ubilabs.net> ;(function($, window, document, undefined){ // ## Options // The default options for this plugin. // // * `map` - Might be a selector, an jQuery object or a DOM element. Default is `false` which shows no map. // * `details` - The container that should be populated with data. Defaults to `false` which ignores the setting. // * `location` - Location to initialize the map on. Might be an address `string` or an `array` with [latitude, longitude] or a `google.maps.LatLng`object. Default is `false` which shows a blank map. // * `bounds` - Whether to snap geocode search to map bounds. Default: `true` if false search globally. Alternatively pass a custom `LatLngBounds object. // * `detailsAttribute` - The attribute's name to use as an indicator. Default: `"name"` // * `mapOptions` - Options to pass to the `google.maps.Map` constructor. See the full list [here](http://code.google.com/apis/maps/documentation/javascript/reference.html#MapOptions). // * `mapOptions.zoom` - The inital zoom level. Default: `14` // * `mapOptions.scrollwheel` - Whether to enable the scrollwheel to zoom the map. Default: `false` // * `mapOptions.mapTypeId` - The map type. Default: `"roadmap"` // * `markerOptions` - The options to pass to the `google.maps.Marker` constructor. See the full list [here](http://code.google.com/apis/maps/documentation/javascript/reference.html#MarkerOptions). // * `markerOptions.draggable` - If the marker is draggable. Default: `false`. Set to true to enable dragging. // * `markerOptions.disabled` - Do not show marker. Default: `false`. Set to true to disable marker. // * `maxZoom` - The maximum zoom level too zoom in after a geocoding response. Default: `16` // * `types` - An array containing one or more of the supported types for the places request. Default: `['geocode']` See the full list [here](http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_requests). var defaults = { bounds: true, country: null, map: false, details: false, detailsAttribute: "name", location: false, mapOptions: { zoom: 14, scrollwheel: false, mapTypeId: "roadmap" }, markerOptions: { draggable: false }, maxZoom: 16, types: ['geocode'] }; // See: [Geocoding Types](https://developers.google.com/maps/documentation/geocoding/#Types) // on Google Developers. var componentTypes = ("street_address route intersection political " + "country administrative_area_level_1 administrative_area_level_2 " + "administrative_area_level_3 colloquial_area locality sublocality " + "neighborhood premise subpremise postal_code natural_feature airport " + "park point_of_interest post_box street_number floor room " + "lat lng viewport location " + "formatted_address location_type bounds").split(" "); // See: [Places Details Responses](https://developers.google.com/maps/documentation/javascript/places#place_details_responses) // on Google Developers. var placesDetails = ("id url website vicinity reference name rating " + "international_phone_number icon formatted_phone_number").split(" "); // The actual plugin constructor. function GeoComplete(input, options) { this.options = $.extend(true, {}, defaults, options); this.input = input; this.$input = $(input); this._defaults = defaults; this._name = 'geocomplete'; this.init(); } // Initialize all parts of the plugin. $.extend(GeoComplete.prototype, { init: function(){ this.initMap(); this.initMarker(); this.initGeocoder(); this.initDetails(); this.initLocation(); }, // Initialize the map but only if the option `map` was set. // This will create a `map` within the given container // using the provided `mapOptions` or link to the existing map instance. initMap: function(){ if (!this.options.map){ return; } if (typeof this.options.map.setCenter == "function"){ this.map = this.options.map; return; } this.map = new google.maps.Map( $(this.options.map)[0], this.options.mapOptions ); }, // Add a marker with the provided `markerOptions` but only // if the option was set. Additionally it listens for the `dragend` event // to notify the plugin about changes. initMarker: function(){ if (!this.map){ return; } var options = $.extend(this.options.markerOptions, { map: this.map }); if (options.disabled){ return; } this.marker = new google.maps.Marker(options); google.maps.event.addListener( this.marker, 'dragend', $.proxy(this.markerDragged, this) ); }, // Associate the input with the autocompleter and create a geocoder // to fall back when the autocompleter does not return a value. initGeocoder: function(){ var options = { types: this.options.types, bounds: this.options.bounds === true ? null : this.options.bounds, componentRestrictions: this.options.componentRestrictions }; if (this.options.country){ options.componentRestrictions = {country: this.options.country} } this.autocomplete = new google.maps.places.Autocomplete( this.input, options ); this.geocoder = new google.maps.Geocoder(); // Bind autocomplete to map bounds but only if there is a map // and `options.bindToMap` is set to true. if (this.map && this.options.bounds === true){ this.autocomplete.bindTo('bounds', this.map); } // Watch `place_changed` events on the autocomplete input field. google.maps.event.addListener( this.autocomplete, 'place_changed', $.proxy(this.placeChanged, this) ); // Prevent parent form from being submitted if user hit enter. this.$input.keypress(function(event){ if (event.keyCode === 13){ return false; } }); // Listen for "geocode" events and trigger find action. this.$input.bind("geocode", $.proxy(function(){ this.find(); }, this)); }, // Prepare a given DOM structure to be populated when we got some data. // This will cycle through the list of component types and map the // corresponding elements. initDetails: function(){ if (!this.options.details){ return; } var $details = $(this.options.details), attribute = this.options.detailsAttribute, details = {}; function setDetail(value){ details[value] = $details.find("[" + attribute + "=" + value + "]"); } $.each(componentTypes, function(index, key){ setDetail(key); setDetail(key + "_short"); }); $.each(placesDetails, function(index, key){ setDetail(key); }); this.$details = $details; this.details = details; }, // Set the initial location of the plugin if the `location` options was set. // This method will care about converting the value into the right format. initLocation: function() { var location = this.options.location, latLng; if (!location) { return; } if (typeof location == 'string') { this.find(location); return; } if (location instanceof Array) { latLng = new google.maps.LatLng(location[0], location[1]); } if (location instanceof google.maps.LatLng){ latLng = location; } if (latLng){ if (this.map){ this.map.setCenter(latLng); } } }, // Look up a given address. If no `address` was specified it uses // the current value of the input. find: function(address){ this.geocode({ address: address || this.$input.val() }); }, // Requests details about a given location. // Additionally it will bias the requests to the provided bounds. geocode: function(request){ if (this.options.bounds && !request.bounds){ if (this.options.bounds === true){ request.bounds = this.map && this.map.getBounds(); } else { request.bounds = this.options.bounds; } } if (this.options.country){ request.region = this.options.country; } this.geocoder.geocode(request, $.proxy(this.handleGeocode, this)); }, // Handles the geocode response. If more than one results was found // it triggers the "geocode:multiple" events. If there was an error // the "geocode:error" event is fired. handleGeocode: function(results, status){ if (status === google.maps.GeocoderStatus.OK) { var result = results[0]; this.$input.val(result.formatted_address); this.update(result); if (results.length > 1){ this.trigger("geocode:multiple", results); } } else { this.trigger("geocode:error", status); } }, // Triggers a given `event` with optional `arguments` on the input. trigger: function(event, argument){ this.$input.trigger(event, [argument]); }, // Set the map to a new center by passing a `geometry`. // If the geometry has a viewport, the map zooms out to fit the bounds. // Additionally it updates the marker position. center: function(geometry){ if (geometry.viewport){ this.map.fitBounds(geometry.viewport); if (this.map.getZoom() > this.options.maxZoom){ this.map.setZoom(this.options.maxZoom); } } else { this.map.setZoom(this.options.maxZoom); this.map.setCenter(geometry.location); } if (this.marker){ this.marker.setPosition(geometry.location); this.marker.setAnimation(this.options.markerOptions.animation); } }, // Update the elements based on a single places or geoocoding response // and trigger the "geocode:result" event on the input. update: function(result){ if (this.map){ this.center(result.geometry); } if (this.$details){ this.fillDetails(result); } this.trigger("geocode:result", result); }, // Populate the provided elements with new `result` data. // This will lookup all elements that has an attribute with the given // component type. fillDetails: function(result){ var data = {}, geometry = result.geometry, viewport = geometry.viewport, bounds = geometry.bounds; // Create a simplified version of the address components. $.each(result.address_components, function(index, object){ var name = object.types[0]; data[name] = object.long_name; data[name + "_short"] = object.short_name; }); // Add properties of the places details. $.each(placesDetails, function(index, key){ data[key] = result[key]; }); // Add infos about the address and geometry. $.extend(data, { formatted_address: result.formatted_address, location_type: geometry.location_type || "PLACES", viewport: viewport, bounds: bounds, location: geometry.location, lat: geometry.location.lat(), lng: geometry.location.lng() }); // Set the values for all details. $.each(this.details, $.proxy(function(key, $detail){ var value = data[key]; this.setDetail($detail, value); }, this)); this.data = data; }, // Assign a given `value` to a single `$element`. // If the element is an input, the value is set, otherwise it updates // the text content. setDetail: function($element, value){ if (value === undefined){ value = ""; } else if (typeof value.toUrlValue == "function"){ value = value.toUrlValue(); } if ($element.is(":input")){ $element.val(value); } else { $element.text(value); } }, // Fire the "geocode:dragged" event and pass the new position. markerDragged: function(event){ this.trigger("geocode:dragged", event.latLng); }, // Restore the old position of the marker to the last now location. resetMarker: function(){ this.marker.setPosition(this.data.location); this.setDetail(this.details.lat, this.data.location.lat()); this.setDetail(this.details.lng, this.data.location.lng()); }, // Update the plugin after the user has selected an autocomplete entry. // If the place has no geometry it passes it to the geocoder. placeChanged: function(){ var place = this.autocomplete.getPlace(); if (!place.geometry){ this.find(place.name); } else { this.update(place); } } }); // A plugin wrapper around the constructor. // Pass `options` with all settings that are different from the default. // The attribute is used to prevent multiple instantiations of the plugin. $.fn.geocomplete = function(options) { var attribute = 'plugin_geocomplete'; // If you call `.geocomplete()` with a string as the first parameter // it returns the corresponding property or calls the method with the // following arguments. if (typeof options == "string"){ var instance = $(this).data(attribute) || $(this).geocomplete().data(attribute), prop = instance[options]; if (typeof prop == "function"){ prop.apply(instance, Array.prototype.slice.call(arguments, 1)); return $(this); } else { if (arguments.length == 2){ prop = arguments[1]; } return prop; } } else { return this.each(function() { // Prevent against multiple instantiations. var instance = $.data(this, attribute); if (!instance) { instance = new GeoComplete( this, options ) $.data(this, attribute, instance); } }); } }; })( jQuery, window, document );
JavaScript
/* * jQuery selectbox plugin * * Copyright (c) 2007 Sadri Sahraoui (brainfault.com) * Licensed under the GPL license and MIT: * http://www.opensource.org/licenses/GPL-license.php * http://www.opensource.org/licenses/mit-license.php * * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete) * * Revision: $Id$ * Version: 0.5 * * Changelog : * Version 0.5 * - separate css style for current selected element and hover element which solve the highlight issue * Version 0.4 * - Fix width when the select is in a hidden div @Pawel Maziarz * - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz */ jQuery.fn.extend({ selectbox: function(options) { return this.each(function() { new jQuery.SelectBox(this, options); }); } }); /* pawel maziarz: work around for ie logging */ if (!window.console) { var console = { log: function(msg) { } } } /* */ jQuery.SelectBox = function(selectobj, options) { var opt = options || {}; opt.inputClass = opt.inputClass || "selectbox3"; opt.containerClass = opt.containerClass || "selectbox-wrapper3"; opt.hoverClass = opt.hoverClass || "current3"; opt.currentClass = opt.selectedClass || "selected3" opt.debug = opt.debug || false; var elm_id = selectobj.id; var active = -1; var inFocus = false; var hasfocus = 0; //jquery object for select element var $select = $(selectobj); // jquery container object var $container = setupContainer(opt); //jquery input object var $input = setupInput(opt); // hide select and append newly created elements $select.hide().before($input).before($container); init(); $input .click(function(){ if (!inFocus) { $container.toggle(); } }) .focus(function(){ if ($container.not(':visible')) { inFocus = true; $container.show(); } }) .keydown(function(event) { switch(event.keyCode) { case 38: // up event.preventDefault(); moveSelect(-1); break; case 40: // down event.preventDefault(); moveSelect(1); break; //case 9: // tab case 13: // return event.preventDefault(); // seems not working in mac ! $('li.'+opt.hoverClass).trigger('click'); break; case 27: //escape hideMe(); break; } }) .blur(function() { if ($container.is(':visible') && hasfocus > 0 ) { if(opt.debug) console.log('container visible and has focus') } else { hideMe(); } }); function hideMe() { hasfocus = 0; $container.hide(); } function init() { $container.append(getSelectOptions($input.attr('id'))).hide(); var width = $input.css('width'); $container.width(width); } function setupContainer(options) { var container = document.createElement("div"); $container = $(container); $container.attr('id', elm_id+'_container'); $container.addClass(options.containerClass); return $container; } function setupInput(options) { var input = document.createElement("input"); var $input = $(input); $input.attr("id", elm_id+"_input"); $input.attr("type", "text"); $input.addClass(options.inputClass); $input.attr("autocomplete", "off"); $input.attr("readonly", "readonly"); $input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie return $input; } function moveSelect(step) { var lis = $("li", $container); if (!lis) return; active += step; if (active < 0) { active = 0; } else if (active >= lis.size()) { active = lis.size() - 1; } lis.removeClass(opt.hoverClass); $(lis[active]).addClass(opt.hoverClass); } function setCurrent() { var li = $("li."+opt.currentClass, $container).get(0); var ar = (''+li.id).split('_'); var el = ar[ar.length-1]; $select.val(el); $input.val($(li).html()); return true; } // select value function getCurrentSelected() { return $select.val(); } // input value function getCurrentValue() { return $input.val(); } function getSelectOptions(parentid) { var select_options = new Array(); var ul = document.createElement('ul'); $select.children('option').each(function() { var li = document.createElement('li'); li.setAttribute('id', parentid + '_' + $(this).val()); li.innerHTML = $(this).html(); if ($(this).is(':selected')) { $input.val($(this).html()); $(li).addClass(opt.currentClass); } ul.appendChild(li); $(li) .mouseover(function(event) { hasfocus = 1; if (opt.debug) console.log('over on : '+this.id); jQuery(event.target, $container).addClass(opt.hoverClass); }) .mouseout(function(event) { hasfocus = -1; if (opt.debug) console.log('out on : '+this.id); jQuery(event.target, $container).removeClass(opt.hoverClass); }) .click(function(event) { var fl = $('li.'+opt.hoverClass, $container).get(0); if (opt.debug) console.log('click on :'+this.id); $('li.'+opt.currentClass).removeClass(opt.currentClass); $(this).addClass(opt.currentClass); setCurrent(); hideMe(); }); }); return ul; } };
JavaScript
/* * Superfish v1.4.8 - jQuery menu widget * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt */ ;(function($){ $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')), over = function(){ var $$ = $(this), menu = getMenu($$); clearTimeout(menu.sfTimer); $$.showSuperfishUl().siblings().hideSuperfishUl(); }, out = function(){ var $$ = $(this), menu = getMenu($$), o = sf.op; clearTimeout(menu.sfTimer); menu.sfTimer=setTimeout(function(){ o.retainPath=($.inArray($$[0],o.$path)>-1); $$.hideSuperfishUl(); if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);} },o.delay); }, getMenu = function($menu){ var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0]; sf.op = sf.o[menu.serial]; return menu; }, addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); }; return this.each(function() { var s = this.serial = sf.o.length; var o = $.extend({},sf.defaults,op); o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){ $(this).addClass([o.hoverClass,c.bcClass].join(' ')) .filter('li:has(ul)').removeClass(o.pathClass); }); sf.o[s] = sf.op = o; $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() { if (o.autoArrows) addArrow( $('>a:first-child',this) ); }) .not('.'+c.bcClass) .hideSuperfishUl(); var $a = $('a',this); $a.each(function(i){ var $li = $a.eq(i).parents('li'); $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);}); }); o.onInit.call(this); }).each(function() { var menuClasses = [c.menuClass]; if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass); $(this).addClass(menuClasses.join(' ')); }); }; var sf = $.fn.superfish; sf.o = []; sf.op = {}; sf.IE7fix = function(){ var o = sf.op; if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined) this.toggleClass(sf.c.shadowClass+'-off'); }; sf.c = { bcClass : 'sf-breadcrumb', menuClass : 'sf-js-enabled', anchorClass : 'sf-with-ul', arrowClass : 'sf-sub-indicator', shadowClass : 'sf-shadow' }; sf.defaults = { hoverClass : 'sfHover', pathClass : 'overideThisToUse', pathLevels : 1, delay : 800, animation : {opacity:'show'}, speed : 'normal', autoArrows : true, dropShadows : true, disableHI : false, // true disables hoverIntent detection onInit : function(){}, // callback functions onBeforeShow: function(){}, onShow : function(){}, onHide : function(){} }; $.fn.extend({ hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass) .find('>ul').hide().css('visibility','hidden'); o.onHide.call($ul); return this; }, showSuperfishUl : function(){ var o = sf.op, sh = sf.c.shadowClass+'-off', $ul = this.addClass(o.hoverClass) .find('>ul:hidden').css('visibility','visible'); sf.IE7fix.call($ul); o.onBeforeShow.call($ul); $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); return this; } }); })(jQuery);
JavaScript
(function($){ /* hoverIntent by Brian Cherne */ $.fn.hoverIntent = function(f,g) { // default configuration options var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; // override configuration options with user supplied object cfg = $.extend(cfg, g ? { over: f, out: g } : f ); // instantiate variables // cX, cY = current X and Y position of mouse, updated by mousemove event // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval var cX, cY, pX, pY; // A private function for getting mouse position var track = function(ev) { cX = ev.pageX; cY = ev.pageY; }; // A private function for comparing current and previous mouse position var compare = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); // compare mouse positions to see if they've crossed the threshold if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { $(ob).unbind("mousemove",track); // set hoverIntent state to true (so mouseOut can be called) ob.hoverIntent_s = 1; return cfg.over.apply(ob,[ev]); } else { // set previous coordinates for next time pX = cX; pY = cY; // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); } }; // A private function for delaying the mouseOut function var delay = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob,[ev]); }; // A private function for handling mouse 'hovering' var handleHover = function(e) { // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } } if ( p == this ) { return false; } // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); var ob = this; // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // else e.type == "onmouseover" if (e.type == "mouseover") { // set "previous" X and Y position based on initial entry point pX = ev.pageX; pY = ev.pageY; // update "current" X and Y position based on mousemove $(ob).bind("mousemove",track); // start polling interval (self-calling timeout) to compare mouse coordinates over time if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} // else e.type == "onmouseout" } else { // unbind expensive mousemove event $(ob).unbind("mousemove",track); // if hoverIntent state is true, then call the mouseOut function after the specified delay if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} } }; // bind the function to the two event listeners return this.mouseover(handleHover).mouseout(handleHover); }; })(jQuery);
JavaScript
/* * Supersubs v0.2b - jQuery plugin * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of * their longest list item children. If you use this, please expect bugs and report them * to the jQuery Google Group with the word 'Superfish' in the subject line. * */ ;(function($){ // $ will refer to jQuery within this closure $.fn.supersubs = function(options){ var opts = $.extend({}, $.fn.supersubs.defaults, options); // return original object to support chaining return this.each(function() { // cache selections var $$ = $(this); // support metadata var o = $.meta ? $.extend({}, opts, $$.data()) : opts; // get the font size of menu. // .css('fontSize') returns various results cross-browser, so measure an em dash instead var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({ 'padding' : 0, 'position' : 'absolute', 'top' : '-999em', 'width' : 'auto' }).appendTo($$).width(); //clientWidth is faster, but was incorrect here // remove em dash $('#menu-fontsize').remove(); // cache all ul elements $ULs = $$.find('ul'); // loop through each ul in menu $ULs.each(function(i) { // cache this ul var $ul = $ULs.eq(i); // get all (li) children of this ul var $LIs = $ul.children(); // get all anchor grand-children var $As = $LIs.children('a'); // force content to one line and save current float property var liFloat = $LIs.css('white-space','nowrap').css('float'); // remove width restrictions and floats so elements remain vertically stacked var emWidth = $ul.add($LIs).add($As).css({ 'float' : 'none', 'width' : 'auto' }) // this ul will now be shrink-wrapped to longest li due to position:absolute // so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer .end().end()[0].clientWidth / fontsize; // add more width to ensure lines don't turn over at certain sizes in various browsers emWidth += o.extraWidth; // restrict to at least minWidth and at most maxWidth if (emWidth > o.maxWidth) { emWidth = o.maxWidth; } else if (emWidth < o.minWidth) { emWidth = o.minWidth; } emWidth += 'em'; // set ul to width in ems $ul.css('width',emWidth); // restore li floats to avoid IE bugs // set li width to full width of this ul // revert white-space to normal $LIs.css({ 'float' : liFloat, 'width' : '100%', 'white-space' : 'normal' }) // update offset position of descendant ul to reflect new width of parent .each(function(){ var $childUl = $('>ul',this); var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right'; $childUl.css(offsetDirection,emWidth); }); }); }); }; // expose defaults $.fn.supersubs.defaults = { minWidth : 9, // requires em unit. maxWidth : 25, // requires em unit. extraWidth : 0 // extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values }; })(jQuery); // plugin code ends
JavaScript
/** * @author trixta */ (function($){ $.bind = function(object, method){ var args = Array.prototype.slice.call(arguments, 2); if(args.length){ return function() { var args2 = [this].concat(args, $.makeArray( arguments )); return method.apply(object, args2); }; } else { return function() { var args2 = [this].concat($.makeArray( arguments )); return method.apply(object, args2); }; } }; })(jQuery);
JavaScript
/** * @author alexander.farkas * @version 1.3 */ (function($){ $.widget('ui.checkBox', { _init: function(){ var that = this, opts = this.options, toggleHover = function(e){ if(this.disabledStatus){ return false; } that.hover = (e.type == 'focus' || e.type == 'mouseenter'); that._changeStateClassChain(); }; if(!this.element.is(':radio,:checkbox')){ return false; } this.labels = $([]); this.checkedStatus = false; this.disabledStatus = false; this.hoverStatus = false; this.radio = (this.element.is(':radio')); this.visualElement = $('<span />') .addClass(this.radio ? 'ui-radio' : 'ui-checkbox') .bind('mouseenter.checkBox mouseleave.checkBox', toggleHover) .bind('click.checkBox', function(e){ that.element[0].click(); //that.element.trigger('click'); return false; }); if (opts.replaceInput) { this.element .addClass('ui-helper-hidden-accessible') .after(this.visualElement[0]) .bind('usermode', function(e){ (e.enabled && that.destroy.call(that, true)); }); } this.element .bind('click.checkBox', $.bind(this, this.reflectUI)) .bind('focus.checkBox blur.checkBox', toggleHover); if(opts.addLabel){ //ToDo: Add Closest Ancestor this.labels = $('label[for=' + this.element.attr('id') + ']') .bind('mouseenter.checkBox mouseleave.checkBox', toggleHover); } this.reflectUI({type: 'initialReflect'}); }, _changeStateClassChain: function(){ var stateClass = (this.checkedStatus) ? '-checked' : '', baseClass = 'ui-'+((this.radio) ? 'radio' : 'checkbox')+'-state'; stateClass += (this.disabledStatus) ? '-disabled' : ''; stateClass += (this.hover) ? '-hover' : ''; if(stateClass){ stateClass = baseClass + stateClass; } function switchStateClass(){ var classes = this.className.split(' '), found = false; $.each(classes, function(i, classN){ if(classN.indexOf(baseClass) === 0){ found = true; classes[i] = stateClass; return false; } }); if(!found){ classes.push(stateClass); } this.className = classes.join(' '); } this.labels.each(switchStateClass); this.visualElement.each(switchStateClass); }, destroy: function(onlyCss){ this.element.removeClass('ui-helper-hidden-accessible'); this.visualElement.addClass('ui-helper-hidden'); if (!onlyCss) { var o = this.options; this.element.unbind('.checkBox'); this.visualElement.remove(); this.labels .unbind('.checkBox') .removeClass('ui-state-hover ui-state-checked ui-state-disabled'); } }, disable: function(){ this.element[0].disabled = true; this.reflectUI({type: 'manuallyDisabled'}); }, enable: function(){ this.element[0].disabled = false; this.reflectUI({type: 'manuallyenabled'}); }, toggle: function(e){ this.changeCheckStatus((this.element.is(':checked')) ? false : true, e); }, changeCheckStatus: function(status, e){ if(e && e.type == 'click' && this.element[0].disabled){ return false; } this.element.attr({'checked': status}); this.reflectUI(e || { type: 'changeCheckStatus' }); }, propagate: function(n, e, _noGroupReflect){ if(!e || e.type != 'initialReflect'){ if (this.radio && !_noGroupReflect) { //dynamic $(document.getElementsByName(this.element.attr('name'))) .checkBox('reflectUI', e, true); } return this._trigger(n, e, { options: this.options, checked: this.checkedStatus, labels: this.labels, disabled: this.disabledStatus }); } }, reflectUI: function(elm, e){ var oldChecked = this.checkedStatus, oldDisabledStatus = this.disabledStatus; e = e || elm; this.disabledStatus = this.element.is(':disabled'); this.checkedStatus = this.element.is(':checked'); if (this.disabledStatus != oldDisabledStatus || this.checkedStatus !== oldChecked) { this._changeStateClassChain(); (this.disabledStatus != oldDisabledStatus && this.propagate('disabledChange', e)); (this.checkedStatus !== oldChecked && this.propagate('change', e)); } } }); $.ui.checkBox.defaults = { replaceInput: true, addLabel: true }; })(jQuery);
JavaScript
// jQuery List DragSort v0.5.1 // Website: http://dragsort.codeplex.com/ // License: http://dragsort.codeplex.com/license (function($) { $.fn.dragsort = function(options) { if (options == "destroy") { $(this.selector).trigger("dragsort-uninit"); return; } var opts = $.extend({}, $.fn.dragsort.defaults, options); var lists = []; var list = null, lastPos = null; this.each(function(i, cont) { //if list container is table, the browser automatically wraps rows in tbody if not specified so change list container to tbody so that children returns rows as user expected if ($(cont).is("table") && $(cont).children().size() == 1 && $(cont).children().is("tbody")) cont = $(cont).children().get(0); var newList = { draggedItem: null, placeHolderItem: null, pos: null, offset: null, offsetLimit: null, scroll: null, container: cont, init: function() { //set options to default values if not set var tagName = $(this.container).children().size() == 0 ? "li" : $(this.container).children(":first").get(0).tagName.toLowerCase(); if (opts.itemSelector == "") opts.itemSelector = tagName; if (opts.dragSelector == "") opts.dragSelector = tagName; if (opts.placeHolderTemplate == "") opts.placeHolderTemplate = "<" + tagName + ">&nbsp;</" + tagName + ">"; //listidx allows reference back to correct list variable instance $(this.container).attr("data-listidx", i).mousedown(this.grabItem).bind("dragsort-uninit", this.uninit); this.styleDragHandlers(true); }, uninit: function() { var list = lists[$(this).attr("data-listidx")]; $(list.container).unbind("mousedown", list.grabItem).unbind("dragsort-uninit"); list.styleDragHandlers(false); }, getItems: function() { return $(this.container).children(opts.itemSelector); }, styleDragHandlers: function(cursor) { this.getItems().map(function() { return $(this).is(opts.dragSelector) ? this : $(this).find(opts.dragSelector).get(); }).css("cursor", cursor ? "pointer" : ""); }, grabItem: function(e) { //if not left click or if clicked on excluded element (e.g. text box) or not a moveable list item return if (e.which != 1 || $(e.target).is(opts.dragSelectorExclude) || $(e.target).closest(opts.dragSelectorExclude).size() > 0 || $(e.target).closest(opts.itemSelector).size() == 0) return; //prevents selection, stops issue on Fx where dragging hyperlink doesn't work and on IE where it triggers mousemove even though mouse hasn't moved, //does also stop being able to click text boxes hence dragging on text boxes by default is disabled in dragSelectorExclude e.preventDefault(); //change cursor to move while dragging var dragHandle = e.target; while (!$(dragHandle).is(opts.dragSelector)) { if (dragHandle == this) return; dragHandle = dragHandle.parentNode; } $(dragHandle).attr("data-cursor", $(dragHandle).css("cursor")); $(dragHandle).css("cursor", "move"); //on mousedown wait for movement of mouse before triggering dragsort script (dragStart) to allow clicking of hyperlinks to work var list = lists[$(this).attr("data-listidx")]; var item = this; var trigger = function() { list.dragStart.call(item, e); $(list.container).unbind("mousemove", trigger); }; $(list.container).mousemove(trigger).mouseup(function() { $(list.container).unbind("mousemove", trigger); $(dragHandle).css("cursor", $(dragHandle).attr("data-cursor")); }); }, dragStart: function(e) { if (list != null && list.draggedItem != null) list.dropItem(); list = lists[$(this).attr("data-listidx")]; list.draggedItem = $(e.target).closest(opts.itemSelector); //record current position so on dragend we know if the dragged item changed position or not list.draggedItem.attr("data-origpos", $(this).attr("data-listidx") + "-" + list.getItems().index(list.draggedItem)); //calculate mouse offset relative to draggedItem var mt = parseInt(list.draggedItem.css("marginTop")); var ml = parseInt(list.draggedItem.css("marginLeft")); list.offset = list.draggedItem.offset(); list.offset.top = e.pageY - list.offset.top + (isNaN(mt) ? 0 : mt) - 1; list.offset.left = e.pageX - list.offset.left + (isNaN(ml) ? 0 : ml) - 1; //calculate box the dragged item can't be dragged outside of if (!opts.dragBetween) { var containerHeight = $(list.container).outerHeight() == 0 ? Math.max(1, Math.round(0.5 + list.getItems().size() * list.draggedItem.outerWidth() / $(list.container).outerWidth())) * list.draggedItem.outerHeight() : $(list.container).outerHeight(); list.offsetLimit = $(list.container).offset(); list.offsetLimit.right = list.offsetLimit.left + $(list.container).outerWidth() - list.draggedItem.outerWidth(); list.offsetLimit.bottom = list.offsetLimit.top + containerHeight - list.draggedItem.outerHeight(); } //create placeholder item var h = list.draggedItem.height(); var w = list.draggedItem.width(); if (opts.itemSelector == "tr") { list.draggedItem.children().each(function() { $(this).width($(this).width()); }); list.placeHolderItem = list.draggedItem.clone().attr("data-placeholder", true); list.draggedItem.after(list.placeHolderItem); list.placeHolderItem.children().each(function() { $(this).css({ borderWidth:0, width: $(this).width() + 1, height: $(this).height() + 1 }).html("&nbsp;"); }); } else { list.draggedItem.after(opts.placeHolderTemplate); list.placeHolderItem = list.draggedItem.next().css({ height: h, width: w }).attr("data-placeholder", true); } if (opts.itemSelector == "td") { var listTable = list.draggedItem.closest("table").get(0); $("<table id='" + listTable.id + "' style='border-width: 0px;' class='dragSortItem " + listTable.className + "'><tr></tr></table>").appendTo("body").children().append(list.draggedItem); } //style draggedItem while dragging var orig = list.draggedItem.attr("style"); list.draggedItem.attr("data-origstyle", orig ? orig : ""); list.draggedItem.css({ position: "absolute", opacity: 0.8, "z-index": 999, height: h, width: w }); //auto-scroll setup list.scroll = { moveX: 0, moveY: 0, maxX: $(document).width() - $(window).width(), maxY: $(document).height() - $(window).height() }; list.scroll.scrollY = window.setInterval(function() { if (opts.scrollContainer != window) { $(opts.scrollContainer).scrollTop($(opts.scrollContainer).scrollTop() + list.scroll.moveY); return; } var t = $(opts.scrollContainer).scrollTop(); if (list.scroll.moveY > 0 && t < list.scroll.maxY || list.scroll.moveY < 0 && t > 0) { $(opts.scrollContainer).scrollTop(t + list.scroll.moveY); list.draggedItem.css("top", list.draggedItem.offset().top + list.scroll.moveY + 1); } }, 10); list.scroll.scrollX = window.setInterval(function() { if (opts.scrollContainer != window) { $(opts.scrollContainer).scrollLeft($(opts.scrollContainer).scrollLeft() + list.scroll.moveX); return; } var l = $(opts.scrollContainer).scrollLeft(); if (list.scroll.moveX > 0 && l < list.scroll.maxX || list.scroll.moveX < 0 && l > 0) { $(opts.scrollContainer).scrollLeft(l + list.scroll.moveX); list.draggedItem.css("left", list.draggedItem.offset().left + list.scroll.moveX + 1); } }, 10); //misc $(lists).each(function(i, l) { l.createDropTargets(); l.buildPositionTable(); }); list.setPos(e.pageX, e.pageY); $(document).bind("mousemove", list.swapItems); $(document).bind("mouseup", list.dropItem); if (opts.scrollContainer != window) $(window).bind("DOMMouseScroll mousewheel", list.wheel); }, //set position of draggedItem setPos: function(x, y) { //remove mouse offset so mouse cursor remains in same place on draggedItem instead of top left corner var top = y - this.offset.top; var left = x - this.offset.left; //limit top, left to within box draggedItem can't be dragged outside of if (!opts.dragBetween) { top = Math.min(this.offsetLimit.bottom, Math.max(top, this.offsetLimit.top)); left = Math.min(this.offsetLimit.right, Math.max(left, this.offsetLimit.left)); } //adjust top, left calculations to parent element instead of window if it's relative or absolute this.draggedItem.parents().each(function() { if ($(this).css("position") != "static" && (!$.browser.mozilla || $(this).css("display") != "table")) { var offset = $(this).offset(); top -= offset.top; left -= offset.left; return false; } }); //set x or y auto-scroll amount if (opts.scrollContainer == window) { y -= $(window).scrollTop(); x -= $(window).scrollLeft(); y = Math.max(0, y - $(window).height() + 5) + Math.min(0, y - 5); x = Math.max(0, x - $(window).width() + 5) + Math.min(0, x - 5); } else { var cont = $(opts.scrollContainer); var offset = cont.offset(); y = Math.max(0, y - cont.height() - offset.top) + Math.min(0, y - offset.top); x = Math.max(0, x - cont.width() - offset.left) + Math.min(0, x - offset.left); } list.scroll.moveX = x == 0 ? 0 : x * opts.scrollSpeed / Math.abs(x); list.scroll.moveY = y == 0 ? 0 : y * opts.scrollSpeed / Math.abs(y); //move draggedItem to new mouse cursor location this.draggedItem.css({ top: top, left: left }); }, //if scroll container is a div allow mouse wheel to scroll div instead of window when mouse is hovering over wheel: function(e) { if (($.browser.safari || $.browser.mozilla) && list && opts.scrollContainer != window) { var cont = $(opts.scrollContainer); var offset = cont.offset(); if (e.pageX > offset.left && e.pageX < offset.left + cont.width() && e.pageY > offset.top && e.pageY < offset.top + cont.height()) { var delta = e.detail ? e.detail * 5 : e.wheelDelta / -2; cont.scrollTop(cont.scrollTop() + delta); e.preventDefault(); } } }, //build a table recording all the positions of the moveable list items buildPositionTable: function() { var pos = []; this.getItems().not([list.draggedItem[0], list.placeHolderItem[0]]).each(function(i) { var loc = $(this).offset(); loc.right = loc.left + $(this).outerWidth(); loc.bottom = loc.top + $(this).outerHeight(); loc.elm = this; pos[i] = loc; }); this.pos = pos; }, dropItem: function() { if (list.draggedItem == null) return; //list.draggedItem.attr("style", "") doesn't work on IE8 and jQuery 1.5 or lower //list.draggedItem.removeAttr("style") doesn't work on chrome and jQuery 1.6 (works jQuery 1.5 or lower) var orig = list.draggedItem.attr("data-origstyle"); list.draggedItem.attr("style", orig); if (orig == "") list.draggedItem.removeAttr("style"); list.draggedItem.removeAttr("data-origstyle"); list.styleDragHandlers(true); list.placeHolderItem.before(list.draggedItem); list.placeHolderItem.remove(); $("[data-droptarget], .dragSortItem").remove(); window.clearInterval(list.scroll.scrollY); window.clearInterval(list.scroll.scrollX); //if position changed call dragEnd if (list.draggedItem.attr("data-origpos") != $(lists).index(list) + "-" + list.getItems().index(list.draggedItem)) opts.dragEnd.apply(list.draggedItem); list.draggedItem.removeAttr("data-origpos"); list.draggedItem = null; $(document).unbind("mousemove", list.swapItems); $(document).unbind("mouseup", list.dropItem); if (opts.scrollContainer != window) $(window).unbind("DOMMouseScroll mousewheel", list.wheel); return false; }, //swap the draggedItem (represented visually by placeholder) with the list item the it has been dragged on top of swapItems: function(e) { if (list.draggedItem == null) return false; //move draggedItem to mouse location list.setPos(e.pageX, e.pageY); //retrieve list and item position mouse cursor is over var ei = list.findPos(e.pageX, e.pageY); var nlist = list; for (var i = 0; ei == -1 && opts.dragBetween && i < lists.length; i++) { ei = lists[i].findPos(e.pageX, e.pageY); nlist = lists[i]; } //if not over another moveable list item return if (ei == -1) return false; //save fixed items locations var children = function() { return $(nlist.container).children().not(nlist.draggedItem); }; var fixed = children().not(opts.itemSelector).each(function(i) { this.idx = children().index(this); }); //if moving draggedItem up or left place placeHolder before list item the dragged item is hovering over otherwise place it after if (lastPos == null || lastPos.top > list.draggedItem.offset().top || lastPos.left > list.draggedItem.offset().left) $(nlist.pos[ei].elm).before(list.placeHolderItem); else $(nlist.pos[ei].elm).after(list.placeHolderItem); //restore fixed items location fixed.each(function() { var elm = children().eq(this.idx).get(0); if (this != elm && children().index(this) < this.idx) $(this).insertAfter(elm); else if (this != elm) $(this).insertBefore(elm); }); //misc $(lists).each(function(i, l) { l.createDropTargets(); l.buildPositionTable(); }); lastPos = list.draggedItem.offset(); return false; }, //returns the index of the list item the mouse is over findPos: function(x, y) { for (var i = 0; i < this.pos.length; i++) { if (this.pos[i].left < x && this.pos[i].right > x && this.pos[i].top < y && this.pos[i].bottom > y) return i; } return -1; }, //create drop targets which are placeholders at the end of other lists to allow dragging straight to the last position createDropTargets: function() { if (!opts.dragBetween) return; $(lists).each(function() { var ph = $(this.container).find("[data-placeholder]"); var dt = $(this.container).find("[data-droptarget]"); if (ph.size() > 0 && dt.size() > 0) dt.remove(); else if (ph.size() == 0 && dt.size() == 0) { if (opts.itemSelector == "td") $(opts.placeHolderTemplate).attr("data-droptarget", true).appendTo(this.container); else //list.placeHolderItem.clone().removeAttr("data-placeholder") crashes in IE7 and jquery 1.5.1 (doesn't in jquery 1.4.2 or IE8) $(this.container).append(list.placeHolderItem.removeAttr("data-placeholder").clone().attr("data-droptarget", true)); list.placeHolderItem.attr("data-placeholder", true); } }); } }; newList.init(); lists.push(newList); }); return this; }; $.fn.dragsort.defaults = { itemSelector: "", dragSelector: "", dragSelectorExclude: "input, textarea", dragEnd: function() { }, dragBetween: false, placeHolderTemplate: "", scrollContainer: window, scrollSpeed: 5 }; })(jQuery);
JavaScript
/** * Really Simple Color Picker in jQuery * * Licensed under the MIT (MIT-LICENSE.txt) licenses. * * Copyright (c) 2008-2012 * Lakshan Perera (www.laktek.com) & Daniel Lacy (daniellacy.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ (function ($) { /** * Create a couple private variables. **/ var selectorOwner, activePalette, cItterate = 0, templates = { control : $('<div class="colorPicker-picker">&nbsp;</div>'), palette : $('<div id="colorPicker_palette" class="colorPicker-palette" />'), swatch : $('<div class="colorPicker-swatch">&nbsp;</div>'), hexLabel: $('<label for="colorPicker_hex">Hex</label>'), hexField: $('<input type="text" id="colorPicker_hex" />') }, transparent = "transparent", lastColor; /** * Create our colorPicker function **/ $.fn.colorPicker = function (options) { return this.each(function () { // Setup time. Clone new elements from our templates, set some IDs, make shortcuts, jazzercise. var element = $(this), opts = $.extend({}, $.fn.colorPicker.defaults, options), defaultColor = $.fn.colorPicker.toHex( (element.val().length > 0) ? element.val() : opts.pickerDefault ), newControl = templates.control.clone(), newPalette = templates.palette.clone().attr('id', 'colorPicker_palette-' + cItterate), newHexLabel = templates.hexLabel.clone(), newHexField = templates.hexField.clone(), paletteId = newPalette[0].id, swatch; /** * Build a color palette. **/ $.each(opts.colors, function (i) { swatch = templates.swatch.clone(); if (opts.colors[i] === transparent) { swatch.addClass(transparent).text('X'); $.fn.colorPicker.bindPalette(newHexField, swatch, transparent); } else { swatch.css("background-color", "#" + this); $.fn.colorPicker.bindPalette(newHexField, swatch); } swatch.appendTo(newPalette); }); newHexLabel.attr('for', 'colorPicker_hex-' + cItterate); newHexField.attr({ 'id' : 'colorPicker_hex-' + cItterate, 'value' : defaultColor }); newHexField.bind("keydown", function (event) { if (event.keyCode === 13) { var hexColor = $.fn.colorPicker.toHex($(this).val()); $.fn.colorPicker.changeColor(hexColor ? hexColor : element.val()); } if (event.keyCode === 27) { $.fn.colorPicker.hidePalette(); } }); newHexField.bind("keyup", function (event) { var hexColor = $.fn.colorPicker.toHex($(event.target).val()); $.fn.colorPicker.previewColor(hexColor ? hexColor : element.val()); }); $('<div class="colorPicker_hexWrap" />').append(newHexLabel).appendTo(newPalette); newPalette.find('.colorPicker_hexWrap').append(newHexField); $("body").append(newPalette); newPalette.hide(); /** * Build replacement interface for original color input. **/ newControl.css("background-color", defaultColor); newControl.bind("click", function () { if( element.is( ':not(:disabled)' ) ) { $.fn.colorPicker.togglePalette($('#' + paletteId), $(this)); } }); if( options && options.onColorChange ) { newControl.data('onColorChange', options.onColorChange); } else { newControl.data('onColorChange', function() {} ); } element.after(newControl); element.bind("change", function () { element.next(".colorPicker-picker").css( "background-color", $.fn.colorPicker.toHex($(this).val()) ); }); // Hide the original input. element.val(defaultColor).hide(); cItterate++; }); }; /** * Extend colorPicker with... all our functionality. **/ $.extend(true, $.fn.colorPicker, { /** * Return a Hex color, convert an RGB value and return Hex, or return false. * * Inspired by http://code.google.com/p/jquery-color-utils **/ toHex : function (color) { // If we have a standard or shorthand Hex color, return that value. if (color.match(/[0-9A-F]{6}|[0-9A-F]{3}$/i)) { return (color.charAt(0) === "#") ? color : ("#" + color); // Alternatively, check for RGB color, then convert and return it as Hex. } else if (color.match(/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/)) { var c = ([parseInt(RegExp.$1, 10), parseInt(RegExp.$2, 10), parseInt(RegExp.$3, 10)]), pad = function (str) { if (str.length < 2) { for (var i = 0, len = 2 - str.length; i < len; i++) { str = '0' + str; } } return str; }; if (c.length === 3) { var r = pad(c[0].toString(16)), g = pad(c[1].toString(16)), b = pad(c[2].toString(16)); return '#' + r + g + b; } // Otherwise we wont do anything. } else { return false; } }, /** * Check whether user clicked on the selector or owner. **/ checkMouse : function (event, paletteId) { var selector = activePalette, selectorParent = $(event.target).parents("#" + selector.attr('id')).length; if (event.target === $(selector)[0] || event.target === selectorOwner[0] || selectorParent > 0) { return; } $.fn.colorPicker.hidePalette(); }, /** * Hide the color palette modal. **/ hidePalette : function () { $(document).unbind("mousedown", $.fn.colorPicker.checkMouse); $('.colorPicker-palette').hide(); }, /** * Show the color palette modal. **/ showPalette : function (palette) { var hexColor = selectorOwner.prev("input").val(); palette.css({ top: selectorOwner.offset().top + (selectorOwner.outerHeight()), left: selectorOwner.offset().left }); $("#color_value").val(hexColor); palette.show(); $(document).bind("mousedown", $.fn.colorPicker.checkMouse); }, /** * Toggle visibility of the colorPicker palette. **/ togglePalette : function (palette, origin) { // selectorOwner is the clicked .colorPicker-picker. if (origin) { selectorOwner = origin; } activePalette = palette; if (activePalette.is(':visible')) { $.fn.colorPicker.hidePalette(); } else { $.fn.colorPicker.showPalette(palette); } }, /** * Update the input with a newly selected color. **/ changeColor : function (value) { selectorOwner.css("background-color", value); selectorOwner.prev("input").val(value).change(); $.fn.colorPicker.hidePalette(); selectorOwner.data('onColorChange').call(selectorOwner, $(selectorOwner).prev("input").attr("id"), value); }, /** * Preview the input with a newly selected color. **/ previewColor : function (value) { selectorOwner.css("background-color", value); }, /** * Bind events to the color palette swatches. */ bindPalette : function (paletteInput, element, color) { color = color ? color : $.fn.colorPicker.toHex(element.css("background-color")); element.bind({ click : function (ev) { lastColor = color; $.fn.colorPicker.changeColor(color); }, mouseover : function (ev) { lastColor = paletteInput.val(); $(this).css("border-color", "#598FEF"); paletteInput.val(color); $.fn.colorPicker.previewColor(color); }, mouseout : function (ev) { $(this).css("border-color", "#000"); paletteInput.val(selectorOwner.css("background-color")); paletteInput.val(lastColor); $.fn.colorPicker.previewColor(lastColor); } }); } }); /** * Default colorPicker options. * * These are publibly available for global modification using a setting such as: * * $.fn.colorPicker.defaults.colors = ['151337', '111111'] * * They can also be applied on a per-bound element basis like so: * * $('#element1').colorPicker({pickerDefault: 'efefef', transparency: true}); * $('#element2').colorPicker({pickerDefault: '333333', colors: ['333333', '111111']}); * **/ $.fn.colorPicker.defaults = { // colorPicker default selected color. pickerDefault : "FFFFFF", // Default color set. colors : [ '000000', '993300', '333300', '000080', '333399', '333333', '800000', 'FF6600', '808000', '008000', '008080', '0000FF', '666699', '808080', 'FF0000', 'FF9900', '99CC00', '339966', '33CCCC', '3366FF', '800080', '999999', 'FF00FF', 'FFCC00', 'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0', 'FF99CC', 'FFCC99', 'FFFF99', 'CCFFFF', '99CCFF', 'FFFFFF' ], // If we want to simply add more colors to the default set, use addColors. addColors : [] }; })(jQuery);
JavaScript
/* * jQuery selectbox plugin * * Copyright (c) 2007 Sadri Sahraoui (brainfault.com) * Licensed under the GPL license and MIT: * http://www.opensource.org/licenses/GPL-license.php * http://www.opensource.org/licenses/mit-license.php * * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete) * * Revision: $Id$ * Version: 0.5 * * Changelog : * Version 0.5 * - separate css style for current selected element and hover element which solve the highlight issue * Version 0.4 * - Fix width when the select is in a hidden div @Pawel Maziarz * - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz */ jQuery.fn.extend({ selectbox: function(options) { return this.each(function() { new jQuery.SelectBox(this, options); }); } }); /* pawel maziarz: work around for ie logging */ if (!window.console) { var console = { log: function(msg) { } } } /* */ jQuery.SelectBox = function(selectobj, options) { var opt = options || {}; opt.inputClass = opt.inputClass || "selectbox"; opt.containerClass = opt.containerClass || "selectbox-wrapper"; opt.hoverClass = opt.hoverClass || "current"; opt.currentClass = opt.selectedClass || "selected" opt.debug = opt.debug || false; var elm_id = selectobj.id; var active = -1; var inFocus = false; var hasfocus = 0; //jquery object for select element var $select = $(selectobj); // jquery container object var $container = setupContainer(opt); //jquery input object var $input = setupInput(opt); // hide select and append newly created elements $select.hide().before($input).before($container); init(); $input .click(function(){ if (!inFocus) { $container.toggle(); } }) .focus(function(){ if ($container.not(':visible')) { inFocus = true; $container.show(); } }) .keydown(function(event) { switch(event.keyCode) { case 38: // up event.preventDefault(); moveSelect(-1); break; case 40: // down event.preventDefault(); moveSelect(1); break; //case 9: // tab case 13: // return event.preventDefault(); // seems not working in mac ! $('li.'+opt.hoverClass).trigger('click'); break; case 27: //escape hideMe(); break; } }) .blur(function() { if ($container.is(':visible') && hasfocus > 0 ) { if(opt.debug) console.log('container visible and has focus') } else { hideMe(); } }); function hideMe() { hasfocus = 0; $container.hide(); } function init() { $container.append(getSelectOptions($input.attr('id'))).hide(); var width = $input.css('width'); $container.width(width); } function setupContainer(options) { var container = document.createElement("div"); $container = $(container); $container.attr('id', elm_id+'_container'); $container.addClass(options.containerClass); return $container; } function setupInput(options) { var input = document.createElement("input"); var $input = $(input); $input.attr("id", elm_id+"_input"); $input.attr("type", "text"); $input.addClass(options.inputClass); $input.attr("autocomplete", "off"); $input.attr("readonly", "readonly"); $input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie return $input; } function moveSelect(step) { var lis = $("li", $container); if (!lis) return; active += step; if (active < 0) { active = 0; } else if (active >= lis.size()) { active = lis.size() - 1; } lis.removeClass(opt.hoverClass); $(lis[active]).addClass(opt.hoverClass); } function setCurrent() { var li = $("li."+opt.currentClass, $container).get(0); var ar = (''+li.id).split('_'); var el = ar[ar.length-1]; $select.val(el); $input.val($(li).html()); return true; } // select value function getCurrentSelected() { return $select.val(); } // input value function getCurrentValue() { return $input.val(); } function getSelectOptions(parentid) { var select_options = new Array(); var ul = document.createElement('ul'); $select.children('option').each(function() { var li = document.createElement('li'); li.setAttribute('id', parentid + '_' + $(this).val()); li.innerHTML = $(this).html(); if ($(this).is(':selected')) { $input.val($(this).html()); $(li).addClass(opt.currentClass); } ul.appendChild(li); $(li) .mouseover(function(event) { hasfocus = 1; if (opt.debug) console.log('over on : '+this.id); jQuery(event.target, $container).addClass(opt.hoverClass); }) .mouseout(function(event) { hasfocus = -1; if (opt.debug) console.log('out on : '+this.id); jQuery(event.target, $container).removeClass(opt.hoverClass); }) .click(function(event) { var fl = $('li.'+opt.hoverClass, $container).get(0); if (opt.debug) console.log('click on :'+this.id); $('li.'+opt.currentClass).removeClass(opt.currentClass); $(this).addClass(opt.currentClass); setCurrent(); hideMe(); }); }); return ul; } };
JavaScript
// ==UserScript== // @name Tieba Voice // @author googleGuard // @version 1.1 // @include http://tieba.baidu.com/* // @run-at document-end // @grant none // ==/UserScript== (function(f){ document.documentElement.appendChild(document.createElement('script')).textContent = '(' + f + ')()' })(function(){ $('body').off('click', '.voice_player a') && $('#j_p_postlist').off('click', '.j_lzl_p_sv') && _.Module.use('common/widget/Voice', {showClientAd: '0', showPostorAd: '0', canPlay: '1'}, function(){$('body').unbind('showvoicedialog')}) })
JavaScript
// ==UserScript== // @name Popup Search // @author lkytal // @namespace Lkytal // @homepage http://coldfire.qiniudn.com/ // @description Popup Search Box and translate Button (etc) for selected Text // @include * // @require http://code.jquery.com/jquery-2.1.1.min.js // @version 2.6.3 // @icon http://lkytal.qiniudn.com/ic.ico // @grant GM_xmlhttpRequest // @grant GM_addStyle // @grant unsafeWindow // @grant GM_openInTab // @grant GM_setClipboard // @grant GM_getClipboard // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @homepageURL https://greasyfork.org/scripts/340-popup-search // ==/UserScript== // Generated by CoffeeScript 1.7.1 if (window != window.top || window.document.title === "") return; var GetOpt, InTextBox, Init, Inter, Load, MouseIn, OpenSet, SetOpt, SettingWin, ShowBar, TimeOutHide, bTrans, baiduico, bingicon, fixPos, getLastRange, get_offsets_and_remove, get_selection_offsets, gicon, ie, pending, ticon, tip, tipdown, tipup, txt; tipdown = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAXElEQVQYlYXMsQ5AQBREUSoVjQ+f+S0lSi2livJlr4ZEZDcmud3JVJIW2yPQVqXZPmwjaQXqEuJJ0vCLbrgDfRZFxBsH0GTRCybbcxF9HhPQZdEHbkUUEUg6JU0Xm2KvCU6v27kAAAAASUVORK5CYII="; tipup = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAZElEQVQYlXXMIQ4CMBBE0UWhwHDw+ddCAhILEgWy4WNo0tAyyZidly1AwNba1CSvJOf6h/oduC/RAN7qfkJ9BC7VM6LhQ1O3E+pN8lAPNeYHHGsV4PkFN3WzREmuwEndLUFVfQC3Xa8Jl+92RAAAAABJRU5ErkJggg=="; tip = tipdown; baiduico = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAGAElEQVRIiVWW649UdxnHz7+gjQTa3Q3sspfZ3dnZnVkWJWVnznVmFo2N+tKkmpY0tk2BFlNbbdIXjZvU1rT2JnaxC0ZswKSRJtjYq1igtEsFsVaBhXBJSwJ7mduZc363jy9+I4kvnhfn9jzP7/s83+/3ONWgguu6eOUSxWArUSng21GVsHQnlco0xWArblQiLAe4rk+58k0Cv4pbDIiCKqEf4fshoR8RBSFR6BP4RQLfpRwFOGEpAqClWkgkaNCJASNQuo1CIzEYQBswgNIAoIREKYWUGqOw3yoBRgCaMPBwKuFdGCAxghRIJChAGJtYGnstBRgDLWGQQGoSpE4Qqo0BjAaZYDvQiqTdIgp9HK8YIRVIoC4TBJAaaKWKREFbwvlLsHgJ2gJaEuoJtA2kdJqRoKRNrqUCIwGJ703jhO40IEl0iuwcXyv7cirhLx8ovrL2R3x17UO8dwxurMLlL6B/dDfT/iyrDVAd6IwxKNlGihZp0qAcuTjVqAgIhEoxaJRSGGUhiWPY9p39jE3tYzi/j+0PfMLSCuQKD5OdnGNg5Hn2zn9OHIM02BxGARKt2rZA4Lso2cboFKPt0LSyeNdj2OK9QnbzQfpHfs9d332PpRuwsW8HualD9GXneexnfyVOoZmCQqMNiNSglMAPijhhGAIarQRGg1Dw7geX+fXcUW7W4PEnP2X9wFP0DTzLc88vsXwT1m+4l/HNr7Gu9xe89Q6sNOw8WkIjdAcuwPddnCDySaWwmAt4/yO4rfthevpmuee+o9Rr8OD9e3hk5x9IYkgSePSn+1jbfTePPH6UGzU4fiol1hAbaKV28AZwfQ8nLEcYoB1LEgXbd73LQH6e8c1v09X1NI1VEC0b9RrUYliNYakOzTbcv+NN1tz+Q/qGfnDrJIkGqQxRpYwTeCFagVLQErDriRMM5H/L2MQR1vc8g2hC2oD6CsztXeTAG9dZjmG1CSs1WLfuMbZs+SNjIy/zk0eP0YihrUBj8MMSTsUvg7ZDjQWcPAu33bGTzOhLFKfnqK3A9S+hu2cn/Zln6Bn8OXeGLxKncP4C9G6YZbJwiOzwXrbf82fawkLUajcJIhen7LqWIAriBOIUjn3U4Ikn32SlCctNyBZmyW36E7mpY2Q3HWdD5nXue/AES6swOj7L4MhT9Pb9mP37L9JOIVEaA0RRgFOOPIyWdsgJaGnJttyEmy2YKu1hePINMuMnyYz/h+H8ImOTp+la/yovvCK5UYNfvrTIgUNXaKXQTEAZK1aeV8LxyiWESjsaAiaFuA2rKYxueYFM4QgDuQUKU1fJ5a+S3XSRofHTZAsnWdf1Grt2X2KpZgff6uiYMhpjFFHo4nhlF41Cy46wKFtgdHKW0a8fZjD/MSOFC4yMLTKau8jo5CUG8+fITl5grHCKDf2/44Edx6lLaAPCgNaWV2FQwqn6/i0dFolV02efO8ZgZp5sfoGhiQWGJ88yMvk5Q4XzDE1cYzD/BUMT1xieOMd4YYG1XU/z4YIg6RSQ0kJeDSo41cDFiBQprKI2BDy0+zCZkcPkxv/N2NS/GN18hszUaYamPiNTuMJw4TqZ/JcMT1wmO36WwZEDvPjqGWJjc1iswZ/2cDx/K8ZaDQ0FTWDuwFV6+18nl/+MkfF/MJT/O4P5j9mYP0l/7lMGcv8kM3GOsfx5JibOsGbNr/jwE9tcqg0gkCJmJvJx/LBEKhMSY0iB5QSW2xBWD9LVs4eejfN09c6R+8ZBZr73N0ozb9M9sJev3f4bBocPcUf3y3z/7neox9DWIKTuqGlCJXBxyl7UMQqs9SFRwGoDLl+FK9eg1rLsrLXtGsYpXFiEI2/VOHFKc7MOzY5pCcmtjfRdDydyQ7s9uuNIutEJe20MSGU7s/utURKU6JBTQ0IneUdGtQKRaGYq2yzRtBIYBVoaQCJFq2Pe/F9xG8pG555EoZBILewPgPif+YPnRjhRuYgfFAm8kJnKtyhNF6mUQyqBS9n3KHtVyl6VyK0QuSFlv2SfeRGB5+OF03iVacLIxfM8KtE2Qq+K55aJwm38F7QH+NcOokk2AAAAAElFTkSuQmCC"; bingicon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACcElEQVRYhe2VX0hTcRTHD0SP9SjUQ4hKbv4pm1u6JhFEVCL2ENGD0UME9haUFAQh0kM9xvRubnebRpFSIVELyRXhsheVIT1kWYIz1MwMy9Qo49PDT7cR5lZe7aH94Dzc3733fD/nd875HZGmMv6ppQHSAGmAv/rJb0c8OxB3AeLKU+YuQDxFiK9kFQH8dkQzs655Nxd6GwmP9TEyM8HIzAThsT4uRnQ2tVYi9TmIb6fBALoV0Yt5MhoBoGUwhD1YzcYb+8m6fYRzPS4W19sv45jbqlKDSEnca2Fz66GYgPhK1LHrNsRfqp49RYgzi2uv22OA0rjNAAB/Keub98TF3fm/j0y3srf9NFp/G+LMRgKOFQIEHIgzm3ezkwBUPjqvIl02VTbEsz018aQAug17sDoefapRGdYF7kJuDoYA6H7/AtHMxoonBdDMDEwNA3Av2oW48tcawMTQ9CgAkQ+vEM20xgCufEIj3fEaqM9ZugYCDsRrUSnSTHHTrSsE8Fo48fRyDKA8VKOEfhXXbdRG/AB8/jbDwKdhxmc/cqyzLjnEsi8DuxBXXgxg/sc84sxS+wnfbLi+j4yWCkS3kXnrcELXZCbvmqRH5LVQ3lETc/p4tBe5ukXdgImgfjuiW8m5czQOoOUaANBUhjTkUhvxxRw/n3yDeItVzr0WdfnoNsRdSEZLxSoALEAceHiGxHV/+BlVnXXYg9U4HpziePgSPRP9cUh3gYEAC+mQhq0c7DhLYCDIy6kos9/nmJv/SnR6jLvRMCe7rqjhpJkMmAVLFqZDVXZjoZqIiy3nylN7Xouqh1T9/TGA0ZYGSAP89wA/AZoF9N4ossasAAAAAElFTkSuQmCC"; ticon = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRQBAwQEBQQFCQUFCRQNCw0UFRQUFBQVEhQUFBQUFRISFBQUFBQVFBIUFBQTDxUUFQ8UDhERDxEVDxAUEhQUDA8PFf/AABEIACAAIAMBEQACEQEDEQH/xAAYAAADAQEAAAAAAAAAAAAAAAAGBwkIBf/EACwQAAIBAwMEAAQHAQAAAAAAAAECAwQFEQYHEgAIITETFEFxFiIjMlFhgQn/xAAYAQADAQEAAAAAAAAAAAAAAAACBAUDBv/EAC0RAAIABQIEBQMFAAAAAAAAAAECAAMEETEFIRIiQfAGE1FhoXGBwRQjseHx/9oADAMBAAIRAxEAPwBLai2xuktz09f7Cpkpb/bI7kjw8l4VMQAq0jI9ukodsL6VlHsAdJI+Vbp2ItMtyGXrBlPsMNyNILq+wU6q0P6F8t9LGSKKfGROiL+YQSD82FB4HIUMFIUOMyW8t8dDGvAk4cS56jvsRzLZtLppnW0agvI0XqaOJZ4LjVVhWmqExygmMiMV4lRx5rnwsTrnjKG0Ykcycw9O+/iAWWL2Ox9YUt6ns9n1JGtJU0qTfMfAljhfKFnyP0z9VJBI+4AHjrZhw7GMTYG4h90vcpabBs5a9K2qwT3y42Wv+bo7okqpHSzg5KIwyGyCVK+iBnwSONKi0Cu1MNUU68uN8GJtbrdBpjCTUPzHewjauwWh47xR2vci1NQ2G53USRXS22qoNTbqpVlZGKnghV8rnKjAYEAEEk87ULOp2alqFsVPXIims6VUKs+SbqRe8AHc12W2nVNwrtY2asrIrowmc2uOl+ZikdoiI44olKiPlLhmkOcF2cnA8XvD2pyNMqfMqk4hjfp74OIj61RVOqUokUz8JBv9fbIz9ftCX03216o0NsvuHdNX26KhhhsFVVUtukqVnaKqXjJ8bimUVgkIXIYn7Y6s+JdcoNSaUlEpuDzMRa4vsBCfhrQ67TEnNWMLEbKN8Dcnv+Y7Gz+we3HcDtjbK+0L+HbrG1NTXdqcF6hFhhMQSIM3BA+Eb4hV8/Cx7DYRovEtZo4MmWoK22v9t/XAta/4h6r8N0Wsss92KsM29rix6fF/mNy7Y6DtW3+irZpyyGeG30LM6GSTnI7M5kcsT75MzE4wPPjHjrl6urm6lUPVVBu7G5inLpZdBKWmkCyqLCCK6UTVH7TjpRgTDciYEzCm7iEobDsRuBWXWqjpKQ2Osg5ytgNJJE0caD+WZ3VQPqWA6FEJYWhx6lSpETm7Xe4Sq2J19WU1xoFu2jLpGamSOF1WrpZwESR4CxAYOoh5RllB4BgQVw1ifTl7FdjE+TO4LqRtFINF91uz2o7VS1NPr+zW0TrlIb1UC3S/bhUcCf8AMjpDyXTYiAmOXN4YL6lsNshaojuUdQsmZCKeQz88+fGCce/6HrpdnUdYNZM2ZsF/ET3/AOlO4N71RXaMtMdTU27TBhrqv5RfCS1cRhETSt9SFlkwp8eSfJAPTlH+6WIGIKqk/pwoJz/Xf+R//9k="; gicon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABzUlEQVRYhe2WTWsTURSGr5iQNOkIgvgDJEIXdqUrUTeltFt3gr/And3afZcuzbo/IC5qksnMtCITrYYWlGAJBKW0fpCNLSiBgtXHxQkmMvdOZkhCicyBs5rLOc+d856Xq9i8wFmmSgASgOkE8CxzThzAzUDtHJRVMG0VGyIegJOCl9fg8zra6DyFipoQgJsDNyuNvLweAMC/In9p7ABlBUcvpEm3DdvX9QAnX2Aj+iiiAThpeH3j30aN2/C9qYdo3hedjAXAs+CZgtNusJE3Yx5FRYE3OwYAW0Hrob5JexUOi/pvn4qRBBkO4OUFwBRbF6WJ8fslcGdGAKgo6JT0xfcfQ7W3+3sP9Gd+vJfxbZoFaQZwM+AXzLcr92bsWaL6n8f6c7vL4JyPCeBZ0uDkq77o27tyeyctaSuoXzXD2mZB6gHcLLya1xfrfhBH3F2CnYV+Nm5BfS6Yb27C88sxAf4ajx8EcDPmm+ri96/eSup1EKKBnCh4MA6eQPtRPAC/EGrN4VtQVfBxrV+sFrJyuuiUhnrBEB+YlVEAvLsH37biAdhKvGQkJ3TS0LgDO4vxmrdWBGAkJxz0BCclphI1a9HeBVP6JkwAEoD/CeAP3U729kMHHe8AAAAASUVORK5CYII="; ie = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAC2ElEQVRYhe2Wy08TURTGSboAlSjKq5SQSlH6cCsLYuIf4FpXLF2oTQpaSqf0YWdciAjRaOKKGGJIQEOIzxgFhZXEKIpPBExQjKJ27i2UdphOp+VzUSEhU8baoiamJ/k2d07u97v33HPn5u05FcS/VF4OIAfwXwBYuCB2n6SochNUMARahkDvobBwfwjAxFLs9FBUupKG207wOHBpAV2PRLyZk/GBxHFxREC5k/wS4rcALByFjiEw+Cj8dyK49SqK4SkJESkBAJgNxuG8HsahrhAujy6hfVBAtZduDICJpdjRTNDzRIRaXBhZwuZGHsUOgraNAjCzFGVOAiokVM1XYi6UQGETD+ZGBDW+LAEsXBBFdh5T3+WUZnJiOeX46EwMx64uwpAtQLWX4mjfosLg3oQELUOw9TiPylaCkWlJkdPQHYIh2xKUthDMBuNrJp74JkNjDWCXj6LWT1Hjo9BYA3gfkBV5ZS0kcwAzR1HZShQr896OoK49iP3n5ldVdyYI9m5EkVvmJLBw6++CKkCtn6K+Yz5ljdON+o55GP0ZAlS1EnQ+ELIC2NeZIYCFoyh28CknbegOId/GY3szWaMCGw+NNbCqfBuvaq4KYPBSHOlNnn4htrbV3n6VUWDjYf5ZWwtHUe4kaOwPo29MxJXHInqfijg7lMVFpHMRDL6TwEcSONgVUuzCwHgURXYeJQ6CLU08mgfCihz7QDjzNixtIRCkZZwfFqCxBvCRxhUGADBDUo9PB2QU2XnVDlAFKHEk2+9wzyL0HgqdiyhKsV4siAloGQIzq26uClDBELz+IuPmyygKm3joGIJNjTzCkvr/4NpzEcUOAlMa5qoAJjZ5wz37FMOLzzH0j0fROyZib1sQRpaifUjAw0kJY7MxDE1KOH1fgJGlqGDI6uHMCmAFQuci0LkIqtwEejeF0U9hZCn07uTbQMskv+s9NO1Vpw3wN5QDyAHkAH4APkBEEJ/n2M4AAAAASUVORK5CYII="; pending = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACGFjVEwAAAANAAAAAHHdBKEAAAAaZmNUTAAAAAAAAAAQAAAAEAAAAAAAAAAAAB4D6AAAOSVkVgAAAZ9JREFUOI2Nkr9r01EUxT+x2CBuXQS1oNAObv4B9l/QqSii4NAqRIMp6qAJvHeDCiIIZhPRoYNDqLiFipH8uCeuHdSpXRXpqoNbHL5fY5oXtQfe8O6579x77rswidA5TrlVTOK33h4mdE4k8TEUiP6A+mCIaSlhTedy7iFQSJ9H36A+GBK1RmjOJny5VST6zVzk9eTjvZWvPjtI8IvcbR9JLfqZsU6A0FnIKvv17K6jmD4R/QP32scAWGsewvSGau9kZqdfoj4YEjoLEP0Rpl2WmzMZ6VuYV9IZ+G3MtwBYbs5g2iXqMZg+YnqRWelfxvQ+HdBvq2oTdCkXfI7pM5i+E1XOg0+wfin1HQ7kfGVUzPwGph9g+kbQlSyxOTtKHscfexVML/NuzmPahrA5N0r4H2rdUwSdToT3oNqbJ+jsvgSnotqbx3wH0zuiX8P6JUyvCJtz+xcpt4oErWBax7RO1OrU7UxgWsp/YcquUyCqTOhf+LtA1J18Tb9i3iBoJevEG5h/yTi//+8uat1Fop5i2sb0Mzu+g3mDWndxMv0Xd/7J/PC3XHUAAAAaZmNUTAAAAAEAAAAQAAAAEAAAAAAAAAAAAB4D6AAAolaOggAAAZlmZEFUAAAAAjiNjZI/a1RREMV/JgTSBD+Ahf82dgELwSZ+AjshgpAUgWXFRHAtRHAD986TFNqI0WbxT6GYIuQbJOElb87aiigiaGuTxsIUdmvxHm/j27dLDly43Jk5c87cgZMg+A1ML+nsnR2d1OpOEXWHB5oZJtAipiOSXp/o6/UE0bdJen2CLtfGF7YmiX6vINmuFq+T9PqYrg3UZEtEPQZOVezM/68kpI3iYRWAR7tnMH0l+kcSbx0rvEBIzwFg2UquNm1A9CeYDlnYmsyD/gnz9rDF7Bamz6Ud0yHmT8H0BdObImkJ0179kICoXYIWi0avMP8Opj+Y3wWgc3A+l1VBCBNFURvT6/x+cD2/m45K/6MwsNcu1ZYwfSNRdyi5DubvidlyRZ7PE7JLxwg/YNlKLcHDndOEdHqsWjq6iOkHph2i3ybqPmv7c+OLqgjpNEFNTO8wbRJ0ZaAwuzpyW4F8Bq3uVD2xmsXGvh3T3W9i+o35BkFNgppEPcf8V76xelZ+6wj5DaJeFHP4mx//ifkGa/uz1fR/oqjJFLqwpRgAAAAaZmNUTAAAAAMAAAAQAAAAEAAAAAAAAAAAAB4D6AAAT8BdawAAAZ5mZEFUAAAABDiNhZIxa1RBFIU/shoUsRNExIgQBG0tFFTwJ9gsooUgrGlijEFE3RVm7oMgpEgQEQzEQqx8FjY2YnTduWf/QUgTsbMJdlrYrcU+nuY9XnJhmuGeb865c2GvMr3HtEXUU3qfT+7ZX6uoa5heY/pJNhwRfbHeNLO6H/Mlgk81gtp5i+jzZMMRpneVV3yRbDgi83MlMKbrmL8hpluVSJd3Ogn96eJiFoDu+nFMG0QJU5fgl+qxfJZsOCL0p8F8CdM2IUwQ+vswbWLpbk30QIcxvSTkk7TzFqZtolbAtIFpDYDe4ASmrHmgngh+Y+w8XSX4FTD9wvxOowgghIkxQAvlY/8N5XeZv6naeatwMI/pVRWwSaZVAB6vH8X83i4RvhD8ZgXgy/+GmE8WW3e7Jl7IDxL1gvsfD1XypbOYPypt9ganMG1h+kTUHJYu1mDBL9AdHGvOHPoHCOpgekvU3E7H6XyxNw+bAY1gdcZifSh/psHBEcyXyXyGoA5RzzD/UYhXdhcDPPl6BtN3TH/Gx78R9ZyQTldb/wKgsMsaKa72kwAAABpmY1RMAAAABQAAABAAAAAQAAAAAAAAAAAAHgPoAACiCi8RAAABo2ZkQVQAAAAGOI2Vk71rVFEQxX/mQ11FsLPxA0HEP0FQIf9DCKiFICRRiCu7EQvdYu48FEFBISC4SCorn52IICpL3pz9B4SkMZ2ICFZiKazFe27Mrs+P083cOeeembkX6mC9/bg+4PEV1zuS7mBxuLb+NwJTpLiEaxnXKq4vZP0BHrf+XeRXzOWTeLRKET3bfuhaxmJmGC92p0nFOTyekIqLI7VnyPoDUtz+afVYZe1KFR/EtU6ScN3E4vSYmxRLZP0BnbdHIOkers+YTWC9KVwbeHF1jHRd+3A9wvKd2PM9WMyw2J0G1zoejwHorB3CldXOIUWBxfnR/r+RYqmWBGA2UQqoPbzsvwTm8smyNlq4VkcFNsjUBeDGmwN4tGqFXD0sLowk4z6uTwA0X+7CY5OkhTFyO2+Q9JB23qCdN3DNcu3VXrDeiWqvZRudtaO43uN6TVITL06NiSUtkPUHWHG8SoRjxdlhgfV2Y5rH9ZSk5jayxcnq3dytbbUWpvnSrV4AO/5OcM3iuozHCh4fK/KD4Vr/iPLzbOL6Xs4kVrZ63sIPq0LKOBaKw/8AAAAaZmNUTAAAAAcAAAAQAAAAEAAAAAAAAAAAAB4D6AAAT5z8+AAAAatmZEFUAAAACDiNjZO/a9NRFMU/sQSK4OIkiAVR/DHpIro4uotQpGDp0qagS624mMB794s4VJCiIIRGhI4pOIhDhULa7z35ByTq4CzWQXBwj8P7mpDkG+mFt9x7OPeee+6Dsgh+A9NXTL+L9wnTM4LPleInCTrnMW0T9RDzNUxvMP0i6/Yxf3o0kvGYb89gvpZItPN/cK1ZJeYLmFqYv6Wxf3lQM90k6/aJvjocN+ruAFA/OIPpM1Ei+iPMGzR0cVSirvJYJwpG38D0k/n2DABR7zCtl04Wdk8SOrOjSVMPU2sIen8cqJQSmNoE3RtP/iH6g2nrSKThWIFdx3xrksDy+wnYOcWTvdMTBP/kJUtbo0XTFzI1AYi+RNTu1EnMPxJ9KWHzRYLfAfMXmH4AleS1ekStTMrIb2PqFXIqmA6JegWhc4ms2ydoGYD6wVlM34jaK7qlhQafo65zqbtWyLr9ob1Rz9OF7V8rdjFL9FVMm9Sa1VEZ+fXipDeGyVqzimmbhl+Zqh8gaDldoT4wzeqSxd3C/DXm34t/sDlw5YgEW5gOMX9JyC+Ml/8CnOPJYMU7mq0AAAAaZmNUTAAAAAkAAAAQAAAAEAAAAAAAAAAAAB4D6AAAou/NpAAAAaNmZEFUAAAACjiNjZM/a5RBEMZ/MSoRaxtBjYJGG8HCPx/AxlpSRMQiGhFFOKMgcge7c4iGEEhjkeiZ0uJASKFgCr27d577AAYlhb3YCBYKdmfxbl713rsjAwszu/M8M/vsLPRb8GNEPcW0ielHWh8xPSH44VJ+yUzzmH5jeol5JV9aw/SdereH+ePRBKE1wb3mvtL+dHMc80pOooXRJDdX9xD8CqYGpgYxm2G6OZ532D5L9f2R4eBq5xCmLUyOaZ7oDzG94v7G/sGAWvsUj7IDf2NNEXR1dIv/mukzpmc7yg3ZaWrtM/0EP4l+J0Vjg4FhV57rDzB/0U/wC8tuJ3+B4LMlgkJAr2BqpNzLRF8nCbYCQPTrRL0begXzDYJfS/5zTFsQtYzpa1HJ9ImouRI46i6mzXSdMUzfMC1BaJ2k3u0RdAOAaucopi9E/1CMbmjtxvSakJ1IZHPUuz1qmtrWYSkn6ZxLgAlMtwitybKgfiGN9OL/Kpu/zQ+y80M12K4c9YbSi4XmXqICQQcHiHep+ExRy8Wz7tiCX8S0Rq19vP/oD5IjysBjq0pjAAAAGmZjVEwAAAALAAAAEAAAABAAAAAAAAAAAAAeA+gAAE95Hk0AAAGmZmRBVAAAAAw4jZWSvWtUURDFf242YKHEXvCrCf4DksJGe8sFERQkuqCEqImyYBbmzisUJKCpJCSidVpBwSgv++ZsIVaGgL2IWCgIYr0Wb7MkebtRB25x75w558zcgb2x8O44SQ9xbeL62T8fcT3A4lgFvys82mTdHq7vuFbxuE3SHVzPcP0oc8XsaIJUXCZFi8baWCVneR2Pu7jO7e8CoLk8jsWlvosVrLhIc3n874WDVvQC13tcc6SYx+MDSUv/TtBan8CsNrg31saw/NBw8E7g/4RZjdb6BLg+4dEAIMU0FlMjRaxzHo+ZEltcxfUVXL/x4iYAHs9JcatCsP0rKeZxrZbYYhbXr9JBiqc7WF+PtJ30BosrfbEVXFvgelJa6Su5tki6PqT4Bq5NzGqY1XB9w7UI7Y3TZN0eKaYBWOicxPWFFK1BsWsO12csPwFAFk2ybo+2JrcBi2TdHtY5Uw4rPzIAA9x/e7ScOGAxVa50PNo95aRXJYmuYXm90oLl9YGy6yVwoDrppKU++4UqQZwtW9Xj/XenrUnu6fAQBwexOLX3+Q9jwc9OVBVYYgAAABpmY1RMAAAADQAAABAAAAAQAAAAAAAAAAAAHgPoAACis2w3AAABrmZkQVQAAAAOOI2Nkz9rFFEUxX+7MZjOwsqAfwqNCJJGEMUP4BdwQbEQFVcUEqOCill4705hEAxoJWs0YpvCQjCCQSc79+wHSNgqvYVgIQq2azHj6u5kJAcG5r17zrn3HngwivlPB4lawLSJ6XvxbRC1QPADJf4/qGF6RNLtY/qG6SXmc0TdxrSM6RchO1ctN3+Ri7NZQqiX6iGdIKS7qg0SP4FlZwBotseJulhMsUTIzv9fPIoHa3uJeovpHtHvEiVMPR529u3cZBQxu8B8Z//gHNLDBD81TArpcVrrR3ZkaHqFaXP0chnzuRL5T6gh1Gm2x/OJ/BbmPyBRG+uczQ38NVEzJYPGylhez24SfbH4n8X0E0xbRH9e7HkZ04fKsaM+Ev1S0WwJUw9MTzH/Muhk6hH9+jbiG8XONUKoY/qK6Qm01o+RdPsEvwJAS0cxf8/M6u58b00S/TOmLUJ6CIDEm7kmmyrcfTG/6JwsB6hJoq4R0oki6NMk3T7RHw+nHLVaFK5WZhCy6Zyjd0BtuNhYGSPq2eAxbfdw7q/twXRnsF5FlylMbzBvVJP+4jefz8z3PhGI6gAAABpmY1RMAAAADwAAABAAAAAQAAAAAAAAAAAAHgPoAABPJb/eAAABqGZkQVQAAAAQOI2Fks9LVFEUxz86ZguXbcVq0UDLCNpE9AeE4GagTQUGRotJySDBoXvP24wgLfqxKMQmaPcWbQJFRGfmnjP/gEaL9gqChNQfMC3uc2De8+mBC5dzv+f7Ped7D+Rjeecq3pqI7SF2kp19Gp0bBWwuRvDWJOn1ETtGbB3RBcReIvaJpe0r55d7+07S6+OtjnOjF6nlivV1VA53B7lG5xaiLUTXcOEhrj1WTuDak4jdG8olehuxN3hdRKyH2D6uPQlALa0g+qroi0vHWdyaKO1S9NsAJ/YHb8086AliX0s7nft8aXAXbSG2NwwQ+4LX+eKIZ5jqdR7RvzkCbeGtXgDX0goAy93rOJ2K2PACsX8g4T7SfRCVdBaxzdIRxLZx+jgTW0PsJ4h9RPRgoCT2Cxdmii3b82zmEZwbRewIb6vQ6Nwk6fVxOhu7CNWh7/HhEV53EfuNa1/L5n8Wa0L11JC3MdG9UzDP2yqJzlHfuAzE/YjrvpIHbsRV1qelHpwaKfoel44PP9TSCt7eRXY9yLyZPpfszHChircPiB0i9uMi+H9sHMtvoD6TpgAAABpmY1RMAAAAEQAAABAAAAAQAAAAAAAAAAAAHgPoAACjJAjOAAABpGZkQVQAAAASOI2Vkr1rFFEUxX/xIxFEQVshLETQf8BGC0n+Bz8g2mjMIhpRE41E4b07qYQQRbQIKKYTtkkTFoXAmLlnsRHBxjQKFkEL0VK02hQzWbIzG4yneu9y7jn3vPugjJDWiJrF9AHTL0yfCOmeCq8nTAlJq43pJ6ZFzKeI2cWdNr8qmm8z0RzYWdMmombz5ux0qX6VRAtEjRLCrk49+FnMY3FJax3nMsLqCNGniVrB9JHgg/m0fpOk1SakR+GODhB1jpDuY3xhL+bzTL7ZX42Y3cD0ldA8CPRh+o7pcckxO0+i95xp7O4Z1XyKmZUjxfkJ5p9LBD0n+mQ1ypb8nZrGMP0pC7wg6laF3Gui6Jcx/S2rXsD0rqdjbnCXkNZyAT3C9AUmmgNYdorQ6Cc0+jF/WTxUNxIfx7TOPT9UiK1jegrBB/M1+vWq49sTRL9G1DKmNe5rqBi/Xqzx+Gaeh3lh9WR3JL+EaZGoK12/0zSMaWYrtQ/TEkmrTfT6tmv8J0xzxa/8RtQzoteJGv0/wQc6hvk8pjVMvzH9ILw+vB19A/CHy5khQV06AAAAGmZjVEwAAAATAAAAEAAAABAAAAAAAAAAAAAeA+gAAE6y2ycAAAGoZmRBVAAAABQ4jZWTO2tUURDHfxt1Y2MjCKIYAgpB/ARiIX4IX0hsNK5IFhVjYbJwZjaVgg8kjeCrE7YQCw0WytU7/20FETQgdqKFaClarcW9LvuKrFOdGeb/mHPmwGCkbBrTMq43uH7ges/h1oahvpFhWqbZ7uD6jushHgtYPjse2PWIZruD6SL11cnxQEPK+cG++pk7m7C4iuWzpDTRrac4goeVSTbdVS7y7aSYKs5pAlMd10tcb1l6vatwGxdotjukbA9c1hZMR6mvTpKyjbjeYfnxYZdxHo81UrYZqOD6iutWf1PKj+Fq/+OeMkxzpYvbuD4ONtzF4tIQ8O/8STtYfLGzPJ/G9WuQ4B4eC0MEo/bA4hSu3wNKcRLT43VH6H1e001cn4qi5wdIrSqpVeVKvm0k2HUWj2dApcw/41qBFFPFDsR8H2BJu/GYx/NzmJ7i+kDj1d7Sfo1mu0NDMyV7XCtXeH+XoBH7cN3H4wGmOVKr2uPmEK7FXr0KFk+KhYra+J9nMCyul06+4FrBoobpxP8RNjSDxw081nD9xPWN9Hzreu1/AJWczMkfsOFuAAAAGmZjVEwAAAAVAAAAEAAAABAAAAAAAAAAAAAeA+gAAKN4qV0AAAGdZmRBVAAAABY4jZWSP2tUURDFfzEaQT+CfxBRIohVqhTiR7CQLYQIgroJoviv0jy4d14qQSUsBLXQgAjCViISCERe3Dn7AbaKqK1YiZVitxb3usF9m5AMXLjMnDlnZjgwHKE6RtQCph6mZ7X6tmEqKbt9TD8wX8Z0fjfNbyi7faLucHNl/5a4Yv0M0Z8CY5vJqIWk3DlXawjVYYJmCGFPFprOUz7KAD+aEn4bgAdrhzB/TWhP5PpxTB8w9Zj/eCQJ+ixlt0+oToB5C9MvGu1xQrUXU4/o92uTRL+FaSOvN4bpO6ZFMG8QdDmBOhcxdbe5U0XpzfT3FqYvw4AXmO7W75D3j51LRH+YcrqK6c8wwSui5msEjfZ4jWwkQelTlD615Qr/iy1i/nVH2NxwgUKTADSf78P0k6ilVLy3epDCT2+O+e5AuoffwDrXiXqP+SdCdWqwUtAMxfrJf+xz2RzTA4XoVzC9xHyZqGsDX4yM0J4g+ttkZZ8dHGrXEf1xduU3opaS47yJeSu5bidRaBLzJ5g2MP3O7zOms6PgfwEtyMus/wVV0wAAABpmY1RMAAAAFwAAABAAAAAQAAAAAAAAAAAAHgPoAABO7nq0AAABoGZkQVQAAAAYOI2Fkr1rVEEUxX9x/ULtF4UECwsLLexEESt7m0UsA2YjihKJhRsDM3cFsQgqiY1NVCyCW6RIEVAWX/bds/+AIBq0sFGrtGq3FvPUuO8luTDFzLlzzpkzF4YrZEcxPcB0roTtWFH3aPcHmDYI+cUS3urWiT5dfdm0RLs/IOoWzad7KntC70zRswyMVCjn5wFodGq0uvV/F3WEG6v7klB+tnA5V4A+lg58CoCZ3mFM74ne2uRuBtM6wceSoE/S7g8I2TEw3ce0QaNTI2S7Mb3D/Hb5iflNTB8KJyOYvmN6DOafMT1PzPllolQdEhD9LTEfL569gOkTRK0QdSmp+EvM75TDC7s2uXhVEExg+jlk06cwv1AiaHRqRV6nMV0FoO1NTL+2dLtjRT3C9KUaDNn+irND/+1b3TqzayerCcwfpsD8OpZfI+oNphfbW7rbG2V27VRSWzlAzMcxLWL+jKArTL8+uD2BaS6NqU9u2fPnN6rBzt6/JOZfMT1JE+dNzOcxfascsDJRdjwl7B8x/SjWOubzhOzEcPtvMOHHU2kn5uQAAAAASUVORK5CYII="; txt = ""; InTextBox = function(selection) { $('textarea, input[type=text], *[contenteditable="true"]', document).each(function(i) { if (selection.containsNode(this, true)) { return true; } }); return false; }; getLastRange = function(selection) { var lastRange, r, _i, _ref; lastRange = selection.getRangeAt(selection.rangeCount - 1); for (r = _i = _ref = selection.rangeCount - 1; _ref <= 0 ? _i <= 0 : _i >= 0; r = _ref <= 0 ? ++_i : --_i) { if (!selection.getRangeAt(r).collapsed) { lastRange = selection.getRangeAt(r); break; } } return lastRange; }; get_offsets_and_remove = function($test_span) { var curr_elem, span_ht, total_offsetLeft, total_offsetTop; curr_elem = $test_span[0]; total_offsetTop = 0; total_offsetLeft = 0; while (curr_elem !== null) { total_offsetTop += curr_elem.offsetTop; total_offsetLeft += curr_elem.offsetLeft; curr_elem = curr_elem.offsetParent; } span_ht = $test_span.height(); $test_span.remove(); return [total_offsetTop, total_offsetLeft, span_ht]; }; get_selection_offsets = function(selection) { var $test_span, lastRange, newRange; $test_span = $('<span class="smarterwiki-popup-bubble-test-span" style="display:inline;">x</span>'); lastRange = getLastRange(selection); newRange = document.createRange(); newRange.setStart(lastRange.endContainer, lastRange.endOffset); newRange.insertNode($test_span[0]); return get_offsets_and_remove($test_span); }; fixPos = function(sel, e) { var fix, m_left, offsetLeft, offsetTop, offsets; offsets = get_selection_offsets(sel); offsetTop = offsets[0]; offsetLeft = offsets[1]; if (e != null) { if (offsetLeft < e.pageX - 100) { offsetLeft = e.pageX; } if (offsetTop < e.pageY - 100) { offsetLeft = e.pageY - 8; } } else { $('#showupbody').css('margin-left', '70px'); } if (GetOpt('#Dis_st')) { offsetTop = offsetTop - 2 - $('#ShowUpBox').height(); if ((offsetTop - document.documentElement.scrollTop) < 40) { offsetTop = document.documentElement.scrollTop + 40; } } else { offsetTop += 1.1 * offsets[2]; } m_left = $('#ShowUpBox').width(); fix = 0; if (offsetLeft - m_left < 4) { fix = 4 - offsetLeft + m_left; } $('#ShowUpBox').css("top", offsetTop + "px").css("left", (offsetLeft - m_left + fix) + "px"); return $('#popuptip').css('margin-left', m_left - 20 - fix); }; MouseIn = 0; bTrans = 0; $(document).mousedown(function(event) { if (bTrans === 1) { $('#ShowUpBox').remove(); Init(); } return $('#ShowUpBox').hide(); }); Inter = void 0; TimeOutHide = function() { if (MouseIn === 0 && GetOpt("#Fade_st") && !bTrans) { return $('#ShowUpBox').fadeOut(600); } }; Init = function() { var $DivBox; $DivBox = $('<span id="ShowUpBox"><span id="showupbody"><span id="popupwapper"></span><span id=Gspan></span></span></span>'); $('body').append($DivBox); $DivBox.hide(); $DivBox[0].style.cssText = "width:auto;height:auto;position:absolute;z-index:10240;display:inline;line-height:0;vertical-align:baseline;"; $('#showupbody')[0].style.cssText = "all: unset;display: block;border:solid 2px rgb(144,144,144);border-radius:1px; background:-moz-linear-gradient(top, rgb(252, 252, 252) 0%, rgb(245, 245, 245) 33%, rgb(245, 245, 245) 100%);background:-webkit-linear-gradient(top, rgb(252, 252, 252), rgb(245, 245, 245));max-width: 750px !important;min-height: 20px;max-height: 350px;min-width: 20px;overflow:auto;"; $('#showupbody')[0].style.cssText = "all: unset;display: block;border:solid 2px rgb(144,144,144);border-radius:1px; background:-moz-linear-gradient(top, rgb(252, 252, 252) 0%, rgb(245, 245, 245) 33%, rgb(245, 245, 245) 100%);background:-webkit-linear-gradient(top, rgb(252, 252, 252), rgb(245, 245, 245));max-width: 750px !important;min-height: 10px;max-height: 350px;min-width: 10px;overflow:auto;"; if (!GetOpt("#Round_st")) { $('#showupbody').css({ "border-radius": "4px" }); } $DivBox.on("mouseup", function(event) { event.stopPropagation(); if (event.which === 3) { event.preventDefault(); GM_setClipboard(document.defaultView.getSelection().toString()); $('#ShowUpBox').remove(); Init(); return false; } else if (event.which === 2) { event.preventDefault(); return GM_openInTab(document.defaultView.getSelection().toString()); } }); $DivBox.on("contextmenu", function(event) { event.stopPropagation(); event.preventDefault(); return false; }); document.getElementById("ShowUpBox").oncontextmenu = function(event) { event.stopPropagation(); event.preventDefault(); return false; }; $DivBox.on("mousedown", function(event) { return event.stopPropagation(); }); $DivBox.on("dblclick", function(event) { return event.stopPropagation(); }); $DivBox.on("click", function(event) { return event.stopPropagation(); }); $DivBox.hover(function() { $(this).fadeTo(150, 1); return MouseIn = 1; }, function() { if (!bTrans) { $(this).fadeTo(300, 0.7); clearTimeout(Inter); Inter = setTimeout(TimeOutHide, 5500); } return MouseIn = 0; }); $('#popupwapper').css({ "margin": "3px 2px 3.8px 2px", "display": "block", "line-height": "0" }); $('#popupwapper').append("<a id=gtransicon href=\"javascript:void(0)\"><img id=gtrans src=\"" + ticon + "\"></img></a>").append("<a id=openurl href=\"\" target=\"_blank\"><img id=iconie src=\"" + ie + "\"></img></a>").append("<a id=sbaidu href=\"\" target=\"_blank\"><img src=\"" + baiduico + "\"></img></a>").append("<a id=sbing href=\"\" target=\"_blank\"><img src=\"" + bingicon + "\"></img></a>").append("<a id=sgoogle href=\"\" target=\"_blank\"><img id=gicon src=\"" + gicon + "\"></img></a>"); $('#sgoogle, #sbing, #sbaidu, #openurl').on("click", function(event) { return $('#ShowUpBox').hide(); }); $('#gtrans').on("click", function(event) { event.preventDefault(); $("#Gspan").empty().append("<div style='padding:5px;'><img src=" + pending + " /></div>").show(); $('#popupwapper').hide(); fixPos(document.defaultView.getSelection()); return GM_xmlhttpRequest({ method: 'POST', url: 'http://203.208.46.200/translate_a/t', data: "client=p&text=" + txt + "&langpair=auto|auto", headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, onload: function(responseDetails) { var Rst, Rtxt, line, means, usage, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; Rtxt = JSON.parse(responseDetails.responseText); Rst = '<div style="padding:10px;font-size:13px;overflow:auto;">'; _ref = Rtxt.sentences; for (_i = 0, _len = _ref.length; _i < _len; _i++) { line = _ref[_i]; Rst += line.trans + '<br>'; } Rst += '<ul style="font-size:13px;list-style-position:inside;">'; if (Rtxt.dict != null) { _ref1 = Rtxt.dict; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { usage = _ref1[_j]; Rst += "<li>" + usage.pos + " : "; _ref2 = usage.entry; for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { means = _ref2[_k]; if (means.score > 0.005 || means.score > usage.entry[0].score / 2) { Rst += means.word + ', '; } } Rst += '</li>'; } } $('#Gspan').empty().append(Rst + '</ul></div>').show(); fixPos(document.defaultView.getSelection()); return bTrans = 1; } }); }); if (!GetOpt('#Open_st')) { $('#openurl').hide(); } if (!GetOpt('#Baidu_st')) { $('#sbaidu').hide(); } if (!GetOpt('#Bing_st')) { $('#sbing').hide(); } if (!GetOpt('#Google_st')) { $('#sgoogle').hide(); } if (GetOpt('#Tab_st')) { $DivBox.find('a').attr('target', '_blank'); } else { $DivBox.find('a').attr('target', '_self'); } if (GetOpt('#Dis_st')) { tip = tipup; $DivBox.append($('<span id=popuptip></span>')); $('#popuptip').css({ 'margin-top': '-2px', 'margin-bottom': '0px' }); } else { tip = tipdown; $DivBox.prepend($('<span id=popuptip></span>')); $('#popuptip').css({ 'margin-top': '0px', 'margin-bottom': '-2px' }); } $('#popuptip').css({ 'background': 'url(' + tip + ') 0px 0px no-repeat transparent', 'display': 'inline-block', 'clear': 'both', 'height': '9px', 'width': '9px' }); $('#Gspan').empty().css({ "line-height": "normal", "width": "auto", "font-size": "16px", "padding": "25px!important", "overflow": "auto" }).hide(); $('#ShowUpBox img').css({ "margin": "0px 2px 0px 2px", "height": "20px", "width": "20px", "border-radius": "1px", "padding": "0px", "display": "inline-block", "-moz-transition-duration": "0.1s" }); $('#ShowUpBox img').hover(function() { return $(this).css({ "margin": "-1px 1px -1px 1px", "height": "22px", "width": "22px" }); }, function() { return $(this).css({ "margin": "0px 2px 0px 2px", "height": "20px", "width": "20px" }); }); return $DivBox.hide(); }; document.onmouseup = function(event) { if (event.which !== 1) { return; } if ($('#Ctrl_st').data('val') && !event.ctrlKey) { return; } window.lxe = event; return setTimeout(function() { return ShowBar(window.lxe); }, 50); }; ShowBar = function(event) { var UrlText, sel, seltxt; sel = document.defaultView.getSelection(); seltxt = sel.toString(); if (seltxt === '' || InTextBox(sel)) { $('#ShowUpBox').hide(); return; } if (GetOpt("#Copy_st")) { GM_setClipboard(seltxt); } txt = encodeURIComponent(seltxt); $('#Gspan').empty().hide(); fixPos(sel, event); $('#sbaidu').attr('href', "http://www.baidu.com/s?wd=" + txt); $('#sbing').attr('href', "https://www.google.com/search?ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:zh-CN:unofficial&client=firefox-nightly&channel=rcs&q=" + txt); $('#sgoogle').attr('href', "https://translate.google.com/?langpair=auto|zh-CN&text=" + txt); UrlText = seltxt; if (UrlText.indexOf('http') === -1) { UrlText = 'http://' + UrlText; } MouseIn = 0; bTrans = 0; clearTimeout(Inter); Inter = setTimeout(TimeOutHide, 4000); $('#openurl').attr('href', UrlText); return $('#ShowUpBox').css('opacity', 0.9).fadeIn(150); }; OpenSet = function() { return $('#popup_setting').show().css('top', '110px'); }; GetOpt = function(id) { return $(id).data('val'); }; SetOpt = function(id) { var dom, val; dom = $("#" + id); val = GM_getValue(id); if (!val) { dom.addClass('close'); } dom.data('val', val); return dom.click(function() { $(this).toggleClass('close'); if ($(this).data('val')) { return $(this).data('val', 0); } else { return $(this).data('val', 1); } }); }; SettingWin = function() { var SaveOpt, item, _i, _len, _ref; GM_addStyle('#popup_setting {all: unset;display:none; transition:0.6s ease top; top:-200%; text-align: justify;position:fixed;left:-moz-calc(50% - 310px);left:-webkit-calc(50% - 310px);width:600px;background:#FFF;box-shadow:0 0 5px #222;padding:20px 10px 50px 20px;z-index:102400;} #rol1,#rol2,#rol3,#rol4,#rol5{text-align: justify;} #popup_save{display:inline-block;position:absolute;right:15px;bottom:10px;} .setting_btn_inside{font-size:16px;padding:4px;-moz-user-select:none;cursor:default;}.setting_btn_inside:hover{background:#DDD;}.setting_btn_inside:active{box-shadow:0 0 3px #999 inset;}'); GM_addStyle('.setting_sp_btn{min-width:120px;height:18px;font-size:12px;padding:4px;-moz-user-select:none;cursor:default;position:relative;margin:5px;margin-right:60px;display:inline-block;} .setting_sp_btn.close{background:#DDD;border:none;} .setting_sp_btn::before{position:absolute;right:-26px;top:0;content:" ";width:26px;height:26px;background:#6B4;transition:0.3s;} .setting_sp_btn.close::before{background:#C54;} .setting_sp_btn:hover{background:#DDD;} .setting_sp_btn:active{box-shadow:0 0 3px #999 inset;}'); $("body").append('<div id="popup_setting"> <div style="font-size:16px;">PopUp设置:请选择需要显示的项目<br><br> </div> <div id="rol1"> </div> <div id="rol2"> </div> <div id="rol3"> </div> <div id="rol4"> </div> <div id = "btnarea"> <div style="font-size:12px;bottom:13px;position:absolute;left:20px;color:red;">请在Greasemonkey的"用户脚本命令"菜单的"Popup Search设置"下打开此选项</div> <div id="popup_save" class="setting_btn_inside" style="display:inline-block;">Save</div> <div id="popup_close" class="setting_btn_inside" style="display:inline-block;position:absolute;right:85px;bottom:10px;">Close</div> </div></div>'); $("#rol1").append('<div id="Google_st">Google搜索</div> <div id="Bing_st">Bing搜索</div> <div id="Baidu_st">Baidu搜索</div>'); $("#rol2").append('<div id="Open_st">选中视作链接打开按钮</div> <div id="Fade_st">超时自动隐藏</div> <div id="Dis_st">显示于文字上方</div>'); $("#rol3").append('<div id="Tab_st"">新标签页打开</div> <div id="Copy_st">选中自动复制</div> <div id="Ctrl_st">仅按下Ctrl时显示</div>'); $("#rol4").append('<div id="Round_st"">弹出框直角风格</div>'); $("#rol1 > div, #rol2 > div, #rol3 > div, #rol4 > div").addClass("setting_sp_btn"); $("#popup_close").click(function() { $("#popup_setting").fadeOut(400, function() { $("#popup_setting").remove(); return SettingWin(); }); }); SaveOpt = function(id) { var dom; dom = $("#" + id); return GM_setValue(id, dom.data('val')); }; _ref = $("#popup_setting .setting_sp_btn"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { item = _ref[_i]; if (item != null) { SetOpt(item.id); } } return $("#popup_save").click(function() { var _j, _len1, _ref1; _ref1 = $("#popup_setting .setting_sp_btn"); for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { item = _ref1[_j]; if (item != null) { SaveOpt(item.id); } } $("#popup_setting").fadeOut(400, function() { $("#popup_setting").remove(); return SettingWin(); }); $('#ShowUpBox').remove(); return Init(); }); }; Load = function() { var UpdateAlert, popupmenu; UpdateAlert = GM_getValue("UpdateAlert", 0); if (UpdateAlert < 4) { GM_setValue("UpdateAlert", 4); GM_setValue("Open_st", GM_getValue("Open_st", 1)); GM_setValue("Baidu_st", GM_getValue("Baidu_st", 1)); GM_setValue("Bing_st", GM_getValue("Bing_st", 1)); GM_setValue("Google_st", GM_getValue("Google_st", 1)); GM_setValue("Fade_st", GM_getValue("Fade_st", 1)); GM_setValue("Ctrl_st", GM_getValue("Ctrl_st", 0)); GM_setValue("Dis_st", GM_getValue("Dis_st", 1)); GM_setValue("Tab_st", GM_getValue("Tab_st", 1)); GM_setValue("Copy_st", GM_getValue("Copy_st", 0)); GM_setValue("Round_st", GM_getValue("Round_st", 1)); SettingWin(); OpenSet(); } else { SettingWin(); } Init(); GM_registerMenuCommand("Popup Search设置", OpenSet, 'p'); if (GM_getValue("PopupMenu", 0)) { popupmenu = document.body.appendChild(document.createElement("menu")); popupmenu.outerHTML = '<menu id="userscript-popup" type="context"><menuitem id="Popupset" label="Popup Search设置"></menuitem></menu>'; document.querySelector("#Popupset").addEventListener("click", OpenSet, false); return document.body.addEventListener("contextmenu", (function() { return document.body.setAttribute("contextmenu", "userscript-popup"); }), false); } }; setTimeout(Load, 100);
JavaScript
// use script only if javascript is availible document.getElementById("questions").className = "questions"; var offset = 0; // set first number as main document.getElementById("cell1").className = "current"; // when back is clicked, change the highlighted number and slide to previous question document.getElementById("prev").onclick = function() { document.getElementById("cell" + (offset+1)).className = ""; offset -= 1; if(offset < 0) offset = 0; document.getElementById("normal").style.marginLeft = offset*(-700)+"px"; document.getElementById("cell" + (offset+1)).className = "current"; }; // when next is clicked, change the highlighted number and slide to next question document.getElementById("next").onclick = function() { document.getElementById("cell" + (offset+1)).className = ""; offset += 1; if(offset > 9) offset = 9; document.getElementById("normal").style.marginLeft = offset*(-700)+"px"; document.getElementById("cell" + (offset+1)).className = "current"; };
JavaScript
// Recent Comment Script for Blogger with Auto Refresh & Notification by Ravi_Rezpector_ID var cm_config_defaults = { home_page: "http://46004600.blogspot.com/", max_result: 17, t_w: 32, t_h: 32, summary: 9999, new_tab_link: true, ct_id: "comments-container", new_cm: " Komentar Baru!", interval: 30000, alert: true }, _cookie = { set: function (g, f, j) { var i, h; if (j) { i = new Date(); i.setTime(i.getTime() + (j * 24 * 60 * 60 * 1000)); h = "; expires=" + i.toGMTString(); } else { h = ""; } document.cookie = g + "=" + f + h + "; path=/"; }, get: function (f) { var e = f + "=", h = document.cookie.split(";"), j; for (var g = 0; g < h.length; g++) { j = h[g]; while (j.charAt(0) == " ") { j = j.substring(1, j.length); } if (j.indexOf(e) == 0) { return j.substring(e.length, j.length); } } return null; }, del: function (b) { this.set(b, "", - 1); } }, tt_cm = (_cookie.get('tt_cm')) ? _cookie.get('tt_cm') : 0, doc_title = document.title; for (var i in cm_config_defaults) { cm_config_defaults[i] = (typeof (cm_config[i]) == 'undefined') ? cm_config_defaults[i] : cm_config[i]; } function showRecentComments(json) { var entry = json.feed.entry, total = parseInt(json.feed.openSearch$totalResults.$t, 10), // Get the comments total skeleton = "", oldCount = tt_cm, // Get the older comments total co = cm_config_defaults; // Compare the older comments total with the new comments total. // If it's greater, then => show the warning of `the new comments total` minus `the older comments total` if (oldCount < total) { if (co.alert === true) { alert((total - oldCount) + co.new_cm); } else if (co.alert === false) { document.title = '(' + (total - oldCount) + co.new_cm + ') ' + doc_title; } else { co.alert((total - oldCount), co.new_cm); } } // Just a recent comments widget skeleton = '<ul class="cm-outer">'; for (var i = 0; i < entry.length; i++) { for (var j = 0; j < entry[i].link.length; j++) { if (entry[i].link[j].rel == 'alternate') { link = entry[i].link[j].href; break; } } var dash = link.lastIndexOf('/') + 1, dot = link.lastIndexOf('.'), title = link.split('-').join(" ").substring(dash, dot) + '&hellip;'; author = entry[i].author[0], name = author.name.$t, avatar = author.gd$image.src.replace(/\/s[0-9]+(\-c|\/)/, "/s" + co.t_w + "$1").replace(/http\:\/\/www.google.com\/url\?source\=imglanding(.*?)q\=/i, "").replace(/\.(jpg|jpeg|png|bmp|gif)(.*?)$/i, ".$1"), profile = (author.uri) ? author.uri.$t : "#nope", date = entry[i].gd$extendedProperty[1].value, content = ("content" in entry[i]) ? entry[i].content.$t.replace(/<br ?\/?>/ig, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : "", nt = (co.new_tab_link) ? ' target="_blank"' : ''; content = (content.length > co.summary) ? content.substring(0, co.summary) + '&hellip;' : content; skeleton += '<li>'; skeleton += '<div class="cm-header"><a href="' + link + '" title="' + title + '"' + nt + '>' + name + '</a><br/>' + date + '</div>'; skeleton += '<div class="cm-content"><a href="' + profile + '" title="' + name + '"' + nt + '><img alt="Loading..." style="width:' + co.t_w + 'px;height:' + co.t_h + 'px;" src="' + avatar + '"></a>'; skeleton += '<span class="cm-text">' + content + '</span>'; skeleton += '</div></li>'; } skeleton += '</ul>'; document.getElementById(co.ct_id).innerHTML = skeleton; _cookie.set('tt_cm', total, 7000); tt_cm = total; // console.log(tt_cm); } (function () { var head = document.getElementsByTagName('head')[0], script = document.createElement('script'), co = cm_config_defaults; script.type = "text/javascript"; script.id = "cm-feed-script"; script.src = co.home_page + "/feeds/comments/default?alt=json-in-script&redirect=false&max-results=" + co.max_result + "&callback=showRecentComments"; head.appendChild(script); setInterval(function () { var newScript = document.createElement('script'); newScript.type = "text/javascript"; newScript.id = "cm-feed-script"; newScript.src = co.home_page + "/feeds/comments/default?alt=json-in-script&redirect=false&max-results=" + co.max_result + "&callback=showRecentComments"; var oldScript = document.getElementById('cm-feed-script'); oldScript.parentNode.removeChild(oldScript); head.appendChild(newScript); }, co.interval); })();
JavaScript
function tabview_aux(TabViewId, id) { var TabView = document.getElementById(TabViewId); // ----- Tabs ----- var Tabs = TabView.firstChild; while (Tabs.className != "Tabs" ) Tabs = Tabs.nextSibling; var Tab = Tabs.firstChild; var i = 0; do { if (Tab.tagName == "A") { i++; Tab.href = "javascript:tabview_switch('"+TabViewId+"', "+i+");"; Tab.className = (i == id) ? "Active" : ""; Tab.blur(); } } while (Tab = Tab.nextSibling); // ----- Pages ----- var Pages = TabView.firstChild; while (Pages.className != 'Pages') Pages = Pages.nextSibling; var Page = Pages.firstChild; var i = 0; do { if (Page.className == 'Page') { i++; if (Pages.offsetHeight) Page.style.height = (Pages.offsetHeight-2)+"px"; Page.style.overflow = "auto"; Page.style.display = (i == id) ? 'block' : 'none'; } } while (Page = Page.nextSibling); } // ----- Functions ------------------------------------------------------------- function tabview_switch(TabViewId, id) { tabview_aux(TabViewId, id); } function tabview_initialize(TabViewId) { tabview_aux(TabViewId, 1); }
JavaScript
<script type='text/javascript'> //<![CDATA[ // sidebar $(function(){$('#sidebar-wrapper .widget-content').hide();$('#sidebar-wrapper h2:first').addClass('active').next().slideDown('slow');$('#sidebar-wrapper h2').css('cursor','pointer').click(function(){$('#sidebar-wrapper h2').removeClass('active').next().slideUp('slow');if($(this).next().is(':hidden')){$(this).addClass('active').next().slideDown('slow')}else{$(this).removeClass('active').next().slideUp('slow')}})}); //]]> </script>
JavaScript
/************************************************************************/ /* Rainbow Links Version 1.03 (2003.9.20) */ /* Script updated by Dynamicdrive.com for IE6 */ /* Copyright (C) 1999-2001 TAKANASHI Mizuki */ /* takanasi@hamal.freemail.ne.jp */ /*----------------------------------------------------------------------*/ /* Read it somehow even if my English text is a little wrong! ;-) */ /* */ /* Usage: */ /* Insert '<script src="rainbow.js"></script>' into the BODY section, */ /* right after the BODY tag itself, before anything else. */ /* You don't need to add "onMouseover" and "onMouseout" attributes!! */ /* */ /* If you'd like to add effect to other texts(not link texts), then */ /* add 'onmouseover="doRainbow(this);"' and */ /* 'onmouseout="stopRainbow();"' to the target tags. */ /* */ /* This Script works with IE4,Netscape6,Mozilla browser and above only, */ /* but no error occurs on other browsers. */ /************************************************************************/ //////////////////////////////////////////////////////////////////// // Setting var rate = 20; // Increase amount(The degree of the transmutation) //////////////////////////////////////////////////////////////////// // Main routine if (document.getElementById) window.onerror=new Function("return true") var objActive; // The object which event occured in var act = 0; // Flag during the action var elmH = 0; // Hue var elmS = 128; // Saturation var elmV = 255; // Value var clrOrg; // A color before the change var TimerID; // Timer ID if (document.all) { document.onmouseover = doRainbowAnchor; document.onmouseout = stopRainbowAnchor; } else if (document.getElementById) { document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT); document.onmouseover = Mozilla_doRainbowAnchor; document.onmouseout = Mozilla_stopRainbowAnchor; } //============================================================================= // doRainbow // This function begins to change a color. //============================================================================= function doRainbow(obj) { if (act == 0) { act = 1; if (obj) objActive = obj; else objActive = event.srcElement; clrOrg = objActive.style.color; TimerID = setInterval("ChangeColor()",100); } } //============================================================================= // stopRainbow // This function stops to change a color. //============================================================================= function stopRainbow() { if (act) { objActive.style.color = clrOrg; clearInterval(TimerID); act = 0; } } //============================================================================= // doRainbowAnchor // This function begins to change a color. (of a anchor, automatically) //============================================================================= function doRainbowAnchor() { if (act == 0) { var obj = event.srcElement; while (obj.tagName != 'A' && obj.tagName != 'BODY') { obj = obj.parentElement; if (obj.tagName == 'A' || obj.tagName == 'BODY') break; } if (obj.tagName == 'A' && obj.href != '') { objActive = obj; act = 1; clrOrg = objActive.style.color; TimerID = setInterval("ChangeColor()",100); } } } //============================================================================= // stopRainbowAnchor // This function stops to change a color. (of a anchor, automatically) //============================================================================= function stopRainbowAnchor() { if (act) { if (objActive.tagName == 'A') { objActive.style.color = clrOrg; clearInterval(TimerID); act = 0; } } } //============================================================================= // Mozilla_doRainbowAnchor(for Netscape6 and Mozilla browser) // This function begins to change a color. (of a anchor, automatically) //============================================================================= function Mozilla_doRainbowAnchor(e) { if (act == 0) { obj = e.target; while (obj.nodeName != 'A' && obj.nodeName != 'BODY') { obj = obj.parentNode; if (obj.nodeName == 'A' || obj.nodeName == 'BODY') break; } if (obj.nodeName == 'A' && obj.href != '') { objActive = obj; act = 1; clrOrg = obj.style.color; TimerID = setInterval("ChangeColor()",100); } } } //============================================================================= // Mozilla_stopRainbowAnchor(for Netscape6 and Mozilla browser) // This function stops to change a color. (of a anchor, automatically) //============================================================================= function Mozilla_stopRainbowAnchor(e) { if (act) { if (objActive.nodeName == 'A') { objActive.style.color = clrOrg; clearInterval(TimerID); act = 0; } } } //============================================================================= // Change Color // This function changes a color actually. //============================================================================= function ChangeColor() { objActive.style.color = makeColor(); } //============================================================================= // makeColor // This function makes rainbow colors. //============================================================================= function makeColor() { // Don't you think Color Gamut to look like Rainbow? // HSVtoRGB if (elmS == 0) { elmR = elmV; elmG = elmV; elmB = elmV; } else { t1 = elmV; t2 = (255 - elmS) * elmV / 255; t3 = elmH % 60; t3 = (t1 - t2) * t3 / 60; if (elmH < 60) { elmR = t1; elmB = t2; elmG = t2 + t3; } else if (elmH < 120) { elmG = t1; elmB = t2; elmR = t1 - t3; } else if (elmH < 180) { elmG = t1; elmR = t2; elmB = t2 + t3; } else if (elmH < 240) { elmB = t1; elmR = t2; elmG = t1 - t3; } else if (elmH < 300) { elmB = t1; elmG = t2; elmR = t2 + t3; } else if (elmH < 360) { elmR = t1; elmG = t2; elmB = t1 - t3; } else { elmR = 0; elmG = 0; elmB = 0; } } elmR = Math.floor(elmR).toString(16); elmG = Math.floor(elmG).toString(16); elmB = Math.floor(elmB).toString(16); if (elmR.length == 1) elmR = "0" + elmR; if (elmG.length == 1) elmG = "0" + elmG; if (elmB.length == 1) elmB = "0" + elmB; elmH = elmH + rate; if (elmH >= 360) elmH = 0; return '#' + elmR + elmG + elmB; }
JavaScript
function toggle_private() { // Search for any private/public links on this page. Store // their old text in "cmd," so we will know what action to // take; and change their text to the opposite action. var cmd = "?"; var elts = document.getElementsByTagName("a"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "privatelink") { cmd = elts[i].innerHTML; elts[i].innerHTML = ((cmd && cmd.substr(0,4)=="show")? "hide&nbsp;private":"show&nbsp;private"); } } // Update all DIVs containing private objects. var elts = document.getElementsByTagName("div"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "private") { elts[i].style.display = ((cmd && cmd.substr(0,4)=="hide")?"none":"block"); } else if (elts[i].className == "public") { elts[i].style.display = ((cmd && cmd.substr(0,4)=="hide")?"block":"none"); } } // Update all table rows containing private objects. Note, we // use "" instead of "block" becaue IE & firefox disagree on what // this should be (block vs table-row), and "" just gives the // default for both browsers. var elts = document.getElementsByTagName("tr"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "private") { elts[i].style.display = ((cmd && cmd.substr(0,4)=="hide")?"none":""); } } // Update all list items containing private objects. var elts = document.getElementsByTagName("li"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "private") { elts[i].style.display = ((cmd && cmd.substr(0,4)=="hide")? "none":""); } } // Update all list items containing private objects. var elts = document.getElementsByTagName("ul"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "private") { elts[i].style.display = ((cmd && cmd.substr(0,4)=="hide")?"none":"block"); } } // Set a cookie to remember the current option. document.cookie = "EpydocPrivate="+cmd; } function show_private() { var elts = document.getElementsByTagName("a"); for(var i=0; i<elts.length; i++) { if (elts[i].className == "privatelink") { cmd = elts[i].innerHTML; if (cmd && cmd.substr(0,4)=="show") toggle_private(); } } } function getCookie(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin != 0) return null; } else { begin += 2; } var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } return unescape(dc.substring(begin + prefix.length, end)); } function setFrame(url1, url2) { parent.frames[1].location.href = url1; parent.frames[2].location.href = url2; } function checkCookie() { var cmd=getCookie("EpydocPrivate"); if (cmd && cmd.substr(0,4)!="show" && location.href.indexOf("#_") < 0) toggle_private(); } function toggleCallGraph(id) { var elt = document.getElementById(id); if (elt.style.display == "none") elt.style.display = "block"; else elt.style.display = "none"; } function expand(id) { var elt = document.getElementById(id+"-expanded"); if (elt) elt.style.display = "block"; var elt = document.getElementById(id+"-expanded-linenums"); if (elt) elt.style.display = "block"; var elt = document.getElementById(id+"-collapsed"); if (elt) { elt.innerHTML = ""; elt.style.display = "none"; } var elt = document.getElementById(id+"-collapsed-linenums"); if (elt) { elt.innerHTML = ""; elt.style.display = "none"; } var elt = document.getElementById(id+"-toggle"); if (elt) { elt.innerHTML = "-"; } } function collapse(id) { var elt = document.getElementById(id+"-expanded"); if (elt) elt.style.display = "none"; var elt = document.getElementById(id+"-expanded-linenums"); if (elt) elt.style.display = "none"; var elt = document.getElementById(id+"-collapsed-linenums"); if (elt) { elt.innerHTML = "<br />"; elt.style.display="block"; } var elt = document.getElementById(id+"-toggle"); if (elt) { elt.innerHTML = "+"; } var elt = document.getElementById(id+"-collapsed"); if (elt) { elt.style.display = "block"; var indent = elt.getAttribute("indent"); var pad = elt.getAttribute("pad"); var s = "<tt class='py-lineno'>"; for (var i=0; i<pad.length; i++) { s += "&nbsp;" } s += "</tt>"; s += "&nbsp;&nbsp;<tt class='py-line'>"; for (var i=0; i<indent.length; i++) { s += "&nbsp;" } s += "<a href='#' onclick='expand(\"" + id; s += "\");return false'>...</a></tt><br />"; elt.innerHTML = s; } } function toggle(id) { elt = document.getElementById(id+"-toggle"); if (elt.innerHTML == "-") collapse(id); else expand(id); return false; } function highlight(id) { var elt = document.getElementById(id+"-def"); if (elt) elt.className = "py-highlight-hdr"; var elt = document.getElementById(id+"-expanded"); if (elt) elt.className = "py-highlight"; var elt = document.getElementById(id+"-collapsed"); if (elt) elt.className = "py-highlight"; } function num_lines(s) { var n = 1; var pos = s.indexOf("\n"); while ( pos > 0) { n += 1; pos = s.indexOf("\n", pos+1); } return n; } // Collapse all blocks that mave more than `min_lines` lines. function collapse_all(min_lines) { var elts = document.getElementsByTagName("div"); for (var i=0; i<elts.length; i++) { var elt = elts[i]; var split = elt.id.indexOf("-"); if (split > 0) if (elt.id.substring(split, elt.id.length) == "-expanded") if (num_lines(elt.innerHTML) > min_lines) collapse(elt.id.substring(0, split)); } } function expandto(href) { var start = href.indexOf("#")+1; if (start != 0 && start != href.length) { if (href.substring(start, href.length) != "-") { collapse_all(4); pos = href.indexOf(".", start); while (pos != -1) { var id = href.substring(start, pos); expand(id); pos = href.indexOf(".", pos+1); } var id = href.substring(start, href.length); expand(id); highlight(id); } } } function kill_doclink(id) { var parent = document.getElementById(id); parent.removeChild(parent.childNodes.item(0)); } function auto_kill_doclink(ev) { if (!ev) var ev = window.event; if (!this.contains(ev.toElement)) { var parent = document.getElementById(this.parentID); parent.removeChild(parent.childNodes.item(0)); } } function doclink(id, name, targets_id) { var elt = document.getElementById(id); // If we already opened the box, then destroy it. // (This case should never occur, but leave it in just in case.) if (elt.childNodes.length > 1) { elt.removeChild(elt.childNodes.item(0)); } else { // The outer box: relative + inline positioning. var box1 = document.createElement("div"); box1.style.position = "relative"; box1.style.display = "inline"; box1.style.top = 0; box1.style.left = 0; // A shadow for fun var shadow = document.createElement("div"); shadow.style.position = "absolute"; shadow.style.left = "-1.3em"; shadow.style.top = "-1.3em"; shadow.style.background = "#404040"; // The inner box: absolute positioning. var box2 = document.createElement("div"); box2.style.position = "relative"; box2.style.border = "1px solid #a0a0a0"; box2.style.left = "-.2em"; box2.style.top = "-.2em"; box2.style.background = "white"; box2.style.padding = ".3em .4em .3em .4em"; box2.style.fontStyle = "normal"; box2.onmouseout=auto_kill_doclink; box2.parentID = id; // Get the targets var targets_elt = document.getElementById(targets_id); var targets = targets_elt.getAttribute("targets"); var links = ""; target_list = targets.split(","); for (var i=0; i<target_list.length; i++) { var target = target_list[i].split("="); links += "<li><a href='" + target[1] + "' style='text-decoration:none'>" + target[0] + "</a></li>"; } // Put it all together. elt.insertBefore(box1, elt.childNodes.item(0)); //box1.appendChild(box2); box1.appendChild(shadow); shadow.appendChild(box2); box2.innerHTML = "Which <b>"+name+"</b> do you want to see documentation for?" + "<ul style='margin-bottom: 0;'>" + links + "<li><a href='#' style='text-decoration:none' " + "onclick='kill_doclink(\""+id+"\");return false;'>"+ "<i>None of the above</i></a></li></ul>"; } return false; } function get_anchor() { var href = location.href; var start = href.indexOf("#")+1; if ((start != 0) && (start != href.length)) return href.substring(start, href.length); } function redirect_url(dottedName) { // Scan through each element of the "pages" list, and check // if "name" matches with any of them. for (var i=0; i<pages.length; i++) { // Each page has the form "<pagename>-m" or "<pagename>-c"; // extract the <pagename> portion & compare it to dottedName. var pagename = pages[i].substring(0, pages[i].length-2); if (pagename == dottedName.substring(0,pagename.length)) { // We've found a page that matches `dottedName`; // construct its URL, using leftover `dottedName` // content to form an anchor. var pagetype = pages[i].charAt(pages[i].length-1); var url = pagename + ((pagetype=="m")?"-module.html": "-class.html"); if (dottedName.length > pagename.length) url += "#" + dottedName.substring(pagename.length+1, dottedName.length); return url; } } }
JavaScript
(function() { function middle_valign_site_header() { var element = $('#site_header'); if (element.length) { if ($(window).innerWidth() >= 768) element.css('margin-top', (element.parent().height() - element.height()) / 2); else element.css('margin-top', ""); } } function set_body() { var window_height = $(window).innerHeight() var body_height = $('body').height(); if (body_height + 60 < window_height) { $('body').height(window_height - 60); } } function scale_height() { var h = 0; $('#nhom_san_pham .row .san_pham_xem_truoc > div').each(function(i, e){ if ($(e).height() > h) {h = $(e).height()} }); $('#nhom_san_pham .row .san_pham_xem_truoc > div').height(h).css('position', 'relative'); $('#nhom_san_pham .row .san_pham_xem_truoc .noi_dung_dai_dien').css('position', 'absolute').css('bottom', '10px').css('width', '100%'); } $(document).ready(function() { set_body(); middle_valign_site_header(); $(window).resize(middle_valign_site_header); $('.tieu_de_slug').keyup(function(){ var _slug = slug($(this).val()); $('.slug_cho_tieu_de').val(_slug); }); $('.datepicker').datepicker() scale_height(); }); })();
JavaScript
/* Holder - 1.9 - client side image placeholders (c) 2012-2013 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //getElementsByClassName polyfill document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s}) //getComputedStyle polyfill window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}) //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} //hasOwnProperty polyfill if (!Object.prototype.hasOwnProperty) Object.prototype.hasOwnProperty = function(prop) { var proto = this.__proto__ || this.constructor.prototype; return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]); } function text_size(width, height, template) { var dimension_arr = [height, width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); return { height: text_height } } function draw(ctx, dimensions, template, ratio) { var ts = text_size(dimensions.width, dimensions.height, template); var text_height = ts.height; var width = dimensions.width * ratio, height = dimensions.height * ratio; var font = template.font ? template.font : "sans-serif"; canvas.width = width; canvas.height = height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, width, height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px "+font; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (ctx.measureText(text).width / width > 1) { text_height = template.size / (ctx.measureText(text).width / width); } //Resetting font size if necessary ctx.font = "bold " + (text_height * ratio) + "px "+font; ctx.fillText(text, (width / 2), (height / 2), width); return canvas.toDataURL("image/png"); } function render(mode, el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text ? decodeURIComponent(holder.text) : holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); theme = (holder.font ? extend(theme, {font: holder.font}) : theme); var ratio = 1; if(window.devicePixelRatio && window.devicePixelRatio > 1){ ratio = window.devicePixelRatio; } if (mode == "image") { el.setAttribute("data-src", src); el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); if(fallback || !holder.auto){ el.style.width = dimensions.width + "px"; el.style.height = dimensions.height + "px"; } if (fallback) { el.style.backgroundColor = theme.background; } else{ el.setAttribute("src", draw(ctx, dimensions, theme, ratio)); } } else { if (!fallback) { el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")"; el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px"; } } }; function fluid(el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var fluid = document.createElement("div"); fluid.style.backgroundColor = theme.background; fluid.style.color = theme.foreground; fluid.className = el.className + " holderjs-fluid"; fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px"); fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px"); fluid.id = el.id; el.style.width=0; el.style.height=0; if (theme.text) { fluid.appendChild(document.createTextNode(theme.text)) } else { fluid.appendChild(document.createTextNode(dimensions_caption)) fluid_images.push(fluid); setTimeout(fluid_update, 0); } el.parentNode.insertBefore(fluid, el.nextSibling) if(window.jQuery){ jQuery(function($){ $(el).on("load", function(){ el.style.width = fluid.style.width; el.style.height = fluid.style.height; $(el).show(); $(fluid).remove(); }); }) } } function fluid_update() { for (i in fluid_images) { if(!fluid_images.hasOwnProperty(i)) continue; var el = fluid_images[i], label = el.firstChild; el.style.lineHeight = el.offsetHeight+"px"; label.data = el.offsetWidth + "x" + el.offsetHeight; } } function parse_flags(flags, options) { var ret = { theme: settings.themes.gray }, render = false; for (sl = flags.length, j = 0; j < sl; j++) { var flag = flags[j]; if (app.flags.dimensions.match(flag)) { render = true; ret.dimensions = app.flags.dimensions.output(flag); } else if (app.flags.fluid.match(flag)) { render = true; ret.dimensions = app.flags.fluid.output(flag); ret.fluid = true; } else if (app.flags.colors.match(flag)) { ret.theme = app.flags.colors.output(flag); } else if (options.themes[flag]) { //If a theme is specified, it will override custom colors ret.theme = options.themes[flag]; } else if (app.flags.text.match(flag)) { ret.text = app.flags.text.output(flag); } else if(app.flags.font.match(flag)){ ret.font = app.flags.font.output(flag); } else if(app.flags.auto.match(flag)){ ret.auto = true; } } return render ? ret : false; }; if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png") .indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var fluid_images = []; var settings = { domain: "holder.js", images: "img", bgnodes: ".holderjs", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } }, stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;margin:0}" }; app.flags = { dimensions: { regex: /^(\d+)x(\d+)$/, output: function (val) { var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, fluid: { regex: /^([0-9%]+)x([0-9%]+)$/, output: function (val) { var exec = this.regex.exec(val); return { width: exec[1], height: exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function (val) { var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } }, font: { regex: /font\:(.*)/, output: function(val){ return this.regex.exec(val)[1]; } }, auto: { regex: /^auto$/ } } for (var flag in app.flags) { if(!app.flags.hasOwnProperty(flag)) continue; app.flags[flag].match = function (val) { return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images = []; if(options.images instanceof window.NodeList){ imageNodes = options.images; } else if(options.images instanceof window.Node){ imageNodes = [options.images]; } else{ imageNodes = selector(options.images); } if(options.elements instanceof window.NodeList){ bgnodes = options.bgnodes; } else if(options.bgnodes instanceof window.Node){ bgnodes = [options.bgnodes]; } else{ bgnodes = selector(options.bgnodes); } preempted = true; for (i = 0, l = imageNodes.length; i < l; i++) images.push(imageNodes[i]); var holdercss = document.getElementById("holderjs-style"); if(!holdercss){ holdercss = document.createElement("style"); holdercss.setAttribute("id", "holderjs-style"); holdercss.type = "text/css"; document.getElementsByTagName("head")[0].appendChild(holdercss); } if(holdercss.styleSheet){ holdercss.styleSheet += options.stylesheet; } else{ holdercss.textContent+= options.stylesheet; } var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)"); for (var l = bgnodes.length, i = 0; i < l; i++) { var src = window.getComputedStyle(bgnodes[i], null) .getPropertyValue("background-image"); var flags = src.match(cssregex); if (flags) { var holder = parse_flags(flags[1].split("/"), options); if (holder) { render("background", bgnodes[i], holder, src); } } } for (var l = images.length, i = 0; i < l; i++) { var src = images[i].getAttribute("src") || images[i].getAttribute("data-src"); if (src != null && src.indexOf(options.domain) >= 0) { var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1) .split("/"), options); if (holder) { if (holder.fluid) { fluid(images[i], holder, src); } else { render("image", images[i], holder, src); } } } } return app; }; contentLoaded(win, function () { if (window.addEventListener) { window.addEventListener("resize", fluid_update, false); window.addEventListener("orientationchange", fluid_update, false); } else { window.attachEvent("onresize", fluid_update) } preempted || app.run(); }); if ( typeof define === "function" && define.amd ) { define( "Holder", [], function () { return app; } ); } })(Holder, window);
JavaScript
var slug = function(str) { str = str.replace(/^\s+|\s+$/g, ''); // trim str = str.toLowerCase(); // remove accents, swap ñ for n, etc var from = "·/_,:;áàảãạặẳắằẵăâấầẩẫậóòỏõọôốồổỗộơớờởỡợéèẻẽẹêếềểễệúùủũụưứừửữựíìĩỉịýỳỷỹỵđ"; var to = "------aaaaaaaaaaaaaaaaaoooooooooooooooooeeeeeeeeeeeuuuuuuuuuuuiiiiiyyyyyd"; for (var i=0, l=from.length ; i<l ; i++) { str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); } str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars .replace(/\s+/g, '-') // collapse whitespace and replace by - .replace(/-+/g, '-'); // collapse dashes return str; };
JavaScript
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require bootstrap-datepicker //= require tinymce-jquery //= require slug //= require_tree .
JavaScript
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD // GO AFTER THE REQUIRES BELOW. // //= require jquery //= require jquery_ujs //= require_tree .
JavaScript
jQuery(document).ready(function() { jQuery('.actionBrowse').click(function() { var itemLocator = jQuery(jQuery(this)).parent().parent(); window.send_to_editor = function(html) { imgurlInput = jQuery('img',html).attr('src'); imgurl = imgurlInput.replace("http://"+window.location.hostname, ""); alert(imgurl); // alert(window.location.hostname); tb_remove(); jQuery(itemLocator).find("input").val(imgurl); jQuery(itemLocator).find("img").attr("src", imgurl) } // alert(imgurl); tb_show('', 'media-upload.php?post_id=1&amp;type=image&amp;TB_iframe=true'); jQuery(itemLocator).find("a").addClass("visible"); return false; }); jQuery('.actionDelete').click(function() { jQuery(jQuery(this)).parent().parent().find("div img").attr("src", "/wp-content/plugins/42A-autos/images/42Autos-img-noauto.jpg") jQuery(jQuery(this)).parent().parent().find("input").val(""); jQuery(jQuery(this)).parent().parent().find("a").removeClass("visible"); return false; }); });
JavaScript
(function() { // Load plugin specific language pack tinymce.PluginManager.requireLangPack('example'); tinymce.create('tinymce.plugins.ExamplePlugin', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('mceExample', function() { ed.windowManager.open({ file : url + '/dialog.htm', width : 320 + ed.getLang('example.delta_width', 0), height : 120 + ed.getLang('example.delta_height', 0), inline : 1 }, { plugin_url : url, // Plugin absolute URL some_custom_arg : 'custom arg' // Custom argument }); }); // Register example button ed.addButton('example', { title : 'example.desc', cmd : 'mceExample', image : url + '/img/example.gif' }); // Add a node change handler, selects the button in the UI when a image is selected ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('example', n.nodeName == 'IMG'); }); }, /** * Creates control instances based in the incomming name. This method is normally not * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons * but you sometimes need to create more complex controls like listboxes, split buttons etc then this * method can be used to create those. * * @param {String} n Name of the control to create. * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control. * @return {tinymce.ui.Control} New control instance or null if no control was created. */ createControl : function(n, cm) { return null; }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Example plugin', author : 'Some author', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example', version : "1.0" }; } }); // Register plugin tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); })();
JavaScript
jQuery(document).ready(function() { jQuery('.actionBrowse').click(function() { var itemLocator = jQuery(jQuery(this)).parent().parent(); window.send_to_editor = function(html) { imgurlInput = jQuery('img',html).attr('src'); imgurl = imgurlInput.replace("http://"+window.location.hostname, ""); alert(imgurl); // alert(window.location.hostname); tb_remove(); jQuery(itemLocator).find("input").val(imgurl); jQuery(itemLocator).find("img").attr("src", imgurl) } // alert(imgurl); tb_show('', 'media-upload.php?post_id=1&amp;type=image&amp;TB_iframe=true'); jQuery(itemLocator).find("a").addClass("visible"); return false; }); jQuery('.actionDelete').click(function() { jQuery(jQuery(this)).parent().parent().find("div img").attr("src", "/wp-content/plugins/42A-autos/images/42Autos-img-noauto.jpg") jQuery(jQuery(this)).parent().parent().find("input").val(""); jQuery(jQuery(this)).parent().parent().find("a").removeClass("visible"); return false; }); });
JavaScript
(function() { // Load plugin specific language pack tinymce.PluginManager.requireLangPack('example'); tinymce.create('tinymce.plugins.ExamplePlugin', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('mceExample', function() { ed.windowManager.open({ file : url + '/dialog.htm', width : 320 + ed.getLang('example.delta_width', 0), height : 120 + ed.getLang('example.delta_height', 0), inline : 1 }, { plugin_url : url, // Plugin absolute URL some_custom_arg : 'custom arg' // Custom argument }); }); // Register example button ed.addButton('example', { title : 'example.desc', cmd : 'mceExample', image : url + '/img/example.gif' }); // Add a node change handler, selects the button in the UI when a image is selected ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('example', n.nodeName == 'IMG'); }); }, /** * Creates control instances based in the incomming name. This method is normally not * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons * but you sometimes need to create more complex controls like listboxes, split buttons etc then this * method can be used to create those. * * @param {String} n Name of the control to create. * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control. * @return {tinymce.ui.Control} New control instance or null if no control was created. */ createControl : function(n, cm) { return null; }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Example plugin', author : 'Some author', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/example', version : "1.0" }; } }); // Register plugin tinymce.PluginManager.add('example', tinymce.plugins.ExamplePlugin); })();
JavaScript
/** * Creates a new Floor. * @constructor * @param {google.maps.Map=} opt_map */ function Floor(opt_map) { /** * @type Array.<google.maps.MVCObject> */ this.overlays_ = []; /** * @type boolean */ this.shown_ = true; if (opt_map) { this.setMap(opt_map); } } /** * @param {google.maps.Map} map */ Floor.prototype.setMap = function(map) { this.map_ = map; }; /** * @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel. * Requires a setMap method. */ Floor.prototype.addOverlay = function(overlay) { if (!overlay) return; this.overlays_.push(overlay); overlay.setMap(this.shown_ ? this.map_ : null); }; /** * Sets the map on all the overlays * @param {google.maps.Map} map The map to set. */ Floor.prototype.setMapAll_ = function(map) { this.shown_ = !!map; for (var i = 0, overlay; overlay = this.overlays_[i]; i++) { overlay.setMap(map); } }; /** * Hides the floor and all associated overlays. */ Floor.prototype.hide = function() { this.setMapAll_(null); }; /** * Shows the floor and all associated overlays. */ Floor.prototype.show = function() { this.setMapAll_(this.map_); };
JavaScript
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
/** * @license * * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview SmartMarker. * * @author Chris Broadfoot (cbro@google.com) */ /** * A google.maps.Marker that has some smarts about the zoom levels it should be * shown. * * Options are the same as google.maps.Marker, with the addition of minZoom and * maxZoom. These zoom levels are inclusive. That is, a SmartMarker with * a minZoom and maxZoom of 13 will only be shown at zoom level 13. * @constructor * @extends google.maps.Marker * @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom. */ function SmartMarker(opts) { var marker = new google.maps.Marker; // default min/max Zoom - shows the marker all the time. marker.setValues({ 'minZoom': 0, 'maxZoom': Infinity }); // the current listener (if any), triggered on map zoom_changed var mapZoomListener; google.maps.event.addListener(marker, 'map_changed', function() { if (mapZoomListener) { google.maps.event.removeListener(mapZoomListener); } var map = marker.getMap(); if (map) { var listener = SmartMarker.newZoomListener_(marker); mapZoomListener = google.maps.event.addListener(map, 'zoom_changed', listener); // Call the listener straight away. The map may already be initialized, // so it will take user input for zoom_changed to be fired. listener(); } }); marker.setValues(opts); return marker; } window['SmartMarker'] = SmartMarker; /** * Creates a new listener to be triggered on 'zoom_changed' event. * Hides and shows the target Marker based on the map's zoom level. * @param {google.maps.Marker} marker The target marker. * @return Function */ SmartMarker.newZoomListener_ = function(marker) { var map = marker.getMap(); return function() { var zoom = map.getZoom(); var minZoom = Number(marker.get('minZoom')); var maxZoom = Number(marker.get('maxZoom')); marker.setVisible(zoom >= minZoom && zoom <= maxZoom); }; };
JavaScript
// Copyright 2011 Google /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript
<!-- The code and license for this plugin can be found at https://github.com/javatechig/phonegap-sms-plugin --> var SmsPlugin = function () {}; SmsPlugin.prototype.send = function (phone, message, method, successCallback, failureCallback) { return cordova.exec(successCallback, failureCallback, 'SmsPlugin', "SendSMS", [phone, message, method]); }; function onDeviceReady() { cordova.addConstructor(function() { cordova.addPlugin("sms", new SmsPlugin()); }); }
JavaScript
jQuery("#scores").buttonset(); jQuery("input[name='scores']", jQuery('#scores')).change( function (e) { if (jQuery(this).val() == "1") { jQuery("#test2").hide(); jQuery("#test1").show(); jQuery("#test3").hide(); } if (jQuery(this).val() == "2") { jQuery("#test1").hide(); jQuery("#test3").hide(); jQuery("#test2").show(); } if (jQuery(this).val() == "3") { jQuery("#test3").show(); jQuery("#test2").hide(); jQuery("#test1").hide(); } }); (function ($) { $(function () { /** * Experimental Draggable points plugin * Revised 2013-02-25 (get latest version from http://jsfiddle.net/highcharts/AyUbx/) * Author: Torstein Hønsi * License: MIT License * */ (function (Highcharts) { var addEvent = Highcharts.addEvent, each = Highcharts.each; var mySeries; /** * Filter by dragMin and dragMax */ Highcharts.Chart.prototype.callbacks.push(function (chart) { var container = chart.container, dragPoint, dragX, dragY, dragPlotX, dragPlotY; chart.redraw(); // kill animation (why was this again?) addEvent(container, 'mousedown', function (e) { var hoverPoint = chart.hoverPoint, options; if (hoverPoint) { options = hoverPoint.series.options; if (options.draggableX) { dragPoint = hoverPoint; mySeries = hoverPoint.series; dragX = e.pageX; dragPlotX = dragPoint.plotX; } if (options.draggableY) { dragPoint = hoverPoint; mySeries = hoverPoint.series; dragY = e.offsetY; dragPlotY = dragPoint.plotY + (chart.plotHeight - (dragPoint.yBottom || chart.plotHeight)); } if (dragPoint) { if (e.offsetX == undefined) { xpos1 = e.pageX - $(chart.container).offset().left; ypos1 = e.pageY - $(chart.container).offset().top; } else { xpos1 = e.offsetX; ypos1 = e.offsetY; } mousePos = chart.yAxis[0].translate(chart.yAxis[0].height - ypos1 + chart.yAxis[0].top, true); isDragging = true; //console.log("Start "+mousePos); chart.mouseIsDown = false; } } }); addEvent(container, 'mousemove', function (e) { if (isDragging) { if (e.offsetX == undefined) { xpos2 = e.pageX - $(chart.container).offset().left; ypos2 = e.pageY - $(chart.container).offset().top; } else { xpos2 = e.offsetX; ypos2 = e.offsetY; } yVar = chart.yAxis[0].translate(chart.yAxis[0].height - ypos2 + chart.yAxis[0].top, true); mySeries.data[0].update({ x: 0, y: yVar }); mySeries.data[1].update({ x: 299, y: yVar }); //mySeries.addPoint([299,yVar],true); /* mySeries.setData(eval("[]")); mySeries.addPoint([1,yVar],true); mySeries.addPoint([299,yVar],true); console.log(yVar); /* for(var g=0;g<2;g++) { mySeries.points[g].y=yVar; } */ chart.redraw(); } //console.log((dragPoint)+" "+(dragPoint.series)+" "+isDragging); }); function drop(e) { isDragging = false; //console.log("End"); } addEvent(document, 'mouseup', drop); addEvent(container, 'mouseleave', drop); }); })(Highcharts); // End plugin to drag charts // jQuery("#slideshow > div:gt(0)").hide(); setInterval(function () { jQuery('#slideshow > div:first') .fadeOut(1) .next() .fadeIn(1) .end() .appendTo('#slideshow'); }, 15000); jQuery("input[name='pages']", jQuery('#pages')).change( function (e) { if (jQuery(this).val() == "1") { jQuery("#test").show(); jQuery("#t1est").hide(); jQuery("#t2est").hide(); } if (jQuery(this).val() == "2") { jQuery("#test").hide(); jQuery("#t1est").show(); jQuery("#t2est").hide(); } if (jQuery(this).val() == "3") { jQuery("#test").hide(); jQuery("#t1est").hide(); jQuery("#t2est").show(); } }); jQuery("#genderslider").slider({ value: 1, min: 11, max: 14, slide: function (event, ui) { jQuery("#gender").html(str[ui.value]); } }); jQuery("#personalityslider").slider({ value: 1, min: 1, max: 5, slide: function (event, ui) { jQuery("#personality").html(str[ui.value]); } }); jQuery("#personality").val('No choice selected'); jQuery("#experienceslider").slider({ value: 6, min: 6, max: 10, slide: function (event, ui) { jQuery("#experience").html(str[ui.value]); } }); jQuery("#experience").val('No choice selected'); jQuery("#reachout").buttonset(); jQuery("#pages").buttonset(); jQuery("input[name='reachout']", jQuery('#reachout')).change( function (e) { if (jQuery(this).val() == "1") { jQuery("#test1234").hide(); jQuery("#test12345").show(); jQuery("#test123456").hide(); } if (jQuery(this).val() == "2") { jQuery("#test1234").hide(); jQuery("#test12345").hide(); jQuery("#test123456").show(); } if (jQuery(this).val() == "3") { jQuery("#test1234").show(); jQuery("#test12345").hide(); jQuery("#test123456").hide(); } }); var str = []; str[0] = "I am a Number Cruncher"; str[1] = "Always liked Maths to Arts"; str[2] = "Neither here. nor there "; str[3] = "Always liked Arts to Maths"; str[4] = "I am a dreamer"; str[5] = "Have no Idea"; str[6] = "I have heard about it"; str[7] = "I have read a little about it"; str[8] = "I have used it at times"; str[9] = "I am a professional"; str[10] = "Somewhere in between"; str[11] = "Male"; str[12] = "Female"; str[13] = "Not comfortable disclosing"; var chart, firstChart = true, sessionScore = [], sessionCount = [], sessionAvg = [], playerPercentile = []; sessionScore[0] = 0, sessionCount[0] = 0, sessionScore[1] = 0, sessionCount[1] = 0, sessionAvg[1] = 0, sessionAvg[1] = 0; var a2Ix = [], a3Ix = [], maxDIx = [], minDIx = [], lastDIx = [], dailyVolIx = [], sumPriceIx = [], score = []; var retrieveIx = 0, displayIx = 0, minDist = 0; var stuck = false, isDragging = false, singlePoint = true;; var pVal = [], nVal = []; var help; var showHelp = true; ///// END OF VAIRBALES var dataPoints = 300, dataPointsInit = 225, dataPointsGap = 250, playerScore; var displayScore = [], averageScore = [], totalCount = [], totalScore = [], totalPlayed = [], countScore = [], percentScore = []; var gamePlayingValue = 1; displayScore[0] = []; displayScore[1] = []; displayScore[0][0] = 'Play Game 1'; displayScore[1][0] = 'Play Game 2'; displayScore[0][1] = 'Play Game 1'; displayScore[1][1] = 'Play Game 2'; displayScore[0][2] = 'Calculating'; displayScore[1][2] = 'Calculating'; jQuery("#radioBtnDiv").buttonset(); $("input[name='view']", $('#radioBtnDiv')).change( function (e) { if ($(this).val() == "singlePoint") { gamePlayingValue = 1; singlePoint = true; chart.series[3].hide(); chart.series[4].hide(); chartUpdate(); //getDataJson(); jQuery("#submitChart").hide(); jQuery("#nextChart").show(); help = 'Click on the coloured area in the right side to predict the chart position'; /* finshedImage.hide(); nextImage.show(); */ } if ($(this).val() == "tradePoint") { gamePlayingValue = 2; singlePoint = false; chart.series[3].show(); chart.series[4].show(); chartUpdate(); getDataJson(); jQuery("#submitChart").show(); jQuery("#nextChart").hide(); help = 'Drag green line (Take Profit) and red line (Stop Loss). If Green line is seen before red line you make that much of profit and vice versa. If no line is touched, you make profit/loss as per the last position of the chart. Click submit at bottom-right after you have decided the position of lines.'; /* finshedImage.show(); nextImage.hide(); */ } }); function createChart() { chart = new Highcharts.Chart({ chart: { renderTo: 'container2', borderColor: 'black', borderWidth: 3, animation: false, events: { click: function (event) { if (singlePoint) { if (stuck) { alert("Click on the Next button below to load the next chart"); } else if (event.xAxis[0].value > dataPointsGap) { stuck = true; pVal[0] = event.xAxis[0].value; pVal[1] = event.yAxis[0].value; chart.series[0].addPoint(pVal); var p = chart.series[0].points[0]; p.update({ marker: { enabled: true, symbol: 'circle', fillColor: "#A0F", lineColor: "#A0F", radius: 5 } }); minDist = 999999999; minX = 0; var ohlcIx = 0; for (var j = dataPointsGap; j < dataPoints; j++) { xd = (j - pVal[0]) * dailyVolIx[displayIx] / 1.5; yd = a2Ix[displayIx][j][4] - pVal[1]; dist = Math.sqrt(xd * xd + yd * yd); if (minDist > dist) { minDist = dist; minX = j; ohlcIx = 4; } yd = a2Ix[displayIx][j][3] - pVal[1]; dist = Math.sqrt(xd * xd + yd * yd); if (minDist > dist) { minDist = dist; minX = j; ohlcIx = 3; } yd = a2Ix[displayIx][j][2] - pVal[1]; dist = Math.sqrt(xd * xd + yd * yd); if (minDist > dist) { minDist = dist; minX = j; ohlcIx = 2; } yd = a2Ix[displayIx][j][1] - pVal[1]; dist = Math.sqrt(xd * xd + yd * yd); if (minDist > dist) { minDist = dist; minX = j; ohlcIx = 1; } } yd = a2Ix[displayIx][minX][1] - pVal[1]; yd = yd * 2 * (maxDIx[displayIx] - minDIx[displayIx]) / (maxDIx[displayIx] + minDIx[displayIx]); dist = Math.sqrt(xd * xd + yd * yd); minDist = 10 * minDist / sumPriceIx[displayIx] * dataPoints * (3 - (minX - dataPointsGap) / (dataPoints - dataPointsGap)); score.push(minDist); sessionCount[0]++; sessionScore[0] = sessionScore[0] + minDist; sessionAvg[0] = sessionScore[0] / sessionCount[0]; totalCount[0] = (countScore[0] + sessionCount[0]); totalScore[0] = (parseInt(averageScore[0]) * countScore[0] + sessionScore[0]) / totalCount[0]; $.ajax({ type: 'GET', url: '/dataFiles/minuteData/updateMinuteAndGetData.php', data: { dataString: minDist.toFixed(2), typeString: 1 }, success: function (dataResponse) { retrieveIx == 14 ? retrieveIx = 1 : retrieveIx++; if (dataResponse.charAt(0) == '[') { originalDataIx = dataResponse; a2Ix[retrieveIx] = $.parseJSON(originalDataIx); a3Ix[retrieveIx] = $.parseJSON(originalDataIx); maxDIx[retrieveIx] = 0, minDIx[retrieveIx] = 9999999, lastDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][dataPointsInit][4]); dailyVolIx[retrieveIx] = 0; sumPriceIx[retrieveIx] = 0; for (var i = 0; i < a2Ix[retrieveIx].length; i++) { if (maxDIx[retrieveIx] < parseFloat(a2Ix[retrieveIx][i][2])) { maxDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][i][2]); } if (minDIx[retrieveIx] > parseFloat(a2Ix[retrieveIx][i][3])) { minDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][i][3]); } } for (var i = 0; i < a2Ix[retrieveIx].length; i++) { a2Ix[retrieveIx][i][1] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][1]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][2] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][2]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][3] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][3]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][4] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][4]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); if (i != 0) dailyVolIx[retrieveIx] = dailyVolIx[retrieveIx] + Math.abs(a2Ix[retrieveIx][i][4] - a2Ix[retrieveIx][i - 1][4]); sumPriceIx[retrieveIx] = sumPriceIx[retrieveIx] + a2Ix[retrieveIx][i][1]; if (i > dataPointsInit) { a3Ix[retrieveIx][i][0] = i + 1; a3Ix[retrieveIx][i][1] = "'-'"; a3Ix[retrieveIx][i][2] = "'-'"; a3Ix[retrieveIx][i][3] = "'-'"; a3Ix[retrieveIx][i][4] = "'-'"; } else { a3Ix[retrieveIx][i][0] = i + 1; a3Ix[retrieveIx][i][1] = a2Ix[retrieveIx][i][1]; a3Ix[retrieveIx][i][2] = a2Ix[retrieveIx][i][2]; a3Ix[retrieveIx][i][3] = a2Ix[retrieveIx][i][3]; a3Ix[retrieveIx][i][4] = a2Ix[retrieveIx][i][4]; } } dailyVolIx[retrieveIx] = dailyVolIx[retrieveIx] / i; if (firstChart == true) { //alert("yipee"); firstChart = false; //chart.hideLoading(); createChart(); chartUpdate(); } } else { a2Ix[retrieveIx] = ""; a3Ix[retrieveIx] = ""; //console.log("Error in data recieved: "+ data); } //console.log("data recieved "+retrieveIx); }, error: function (jqXHR, exception) { //console.log("Error in getting Data. Sorry for the issue. Please come back later."); a2Ix[retrieveIx] = ""; a3Ix[retrieveIx] = ""; } }); updateDisplayScore(minDist.toFixed(2) + " points", 0, 0); updateDisplayScore(sessionScore[0].toFixed(2) + " pts " + sessionCount[0] + " plays", 0, 1); updateDisplayScore(totalScore[0].toFixed(2) + " pts " + totalCount[0] + " plays", 0, 2); nVal[0] = minX; nVal[1] = chart.series[1].points[minX].y; chart.series[0].addPoint(nVal); chart.series[1].show(); chart.series[2].hide(); chart.yAxis[0].setExtremes(null, null); pVal = []; nVal = []; } } } } }, xAxis: { labels: { enabled: false }, title: { text: null }, plotBands: [{ // mark the weekend color: '#FFF', from: 1, to: dataPointsInit, events: { mouseover: function (event) { $(chart.container).css('cursor', 'default'); } } }, { // mark the weekend color: '#e7e7e7', from: dataPointsInit + 1, to: dataPointsGap, events: { mouseover: function (event) { $(chart.container).css('cursor', 'none'); } } }, { // mark the weekend color: '#E0BEFF', from: dataPointsGap, to: dataPoints, events: { mousemove: function (event) { $(chart.container).css('cursor', 'default'); } } }] }, yAxis: { labels: { enabled: false }, title: { text: null } }, plotOptions: { series: { cursor: 'ns-resize', stickyTracking: false, states: { hover: { enabled: false } } } }, legend: { enabled: false, borderWidth: 2, useHTML: true, symbolWidth: 0, symbolPadding: 0, shadow: true, floating: true, align: 'left', verticalAlign: 'top' }, tooltip: { enabled: true, borderWidth: 0, useHTML: true, shared: false, shadow: true, /*positioner: function(boxWidth, boxHeight, point) { return {x:2,y:chart.chartHeight/2}; },*/ formatter: function () { true; if (gamePlayingValue == 1) { if (stuck == false) { help = 'Click on the coloured area in the right side to predict the chart position'; } else { help = 'Click on the "Next Chart" button at the bottom-right to see the next chart'; } } else { if (stuck == false) { help = 'Step 1: Drag green line (Take Profit) and red line (Stop Loss). <br> Step 2: Click submit at bottom-right after you have decided the position of lines.'; } else { help = 'Click on the "Next Chart" button at the bottom-right to see the next chart'; } } if (showHelp) { return help; } else { return ''; } } }, navigator: { enabled: false }, scrollbar: { enabled: false }, rangeSelector: { enabled: false }, title: { text: '' }, series: [{ type: 'line', color: 'yellow', showInLegend: false, data: [] }, { showInLegend: false, type: 'candlestick', animation: false, data: [] }, { showInLegend: true, type: 'candlestick', animation: false, color: '#CCC', data: [] }, { showInLegend: false, animation: false, marker: { enabled: false }, color: 'green', draggableY: true, data: [] }, { showInLegend: false, animation: false, marker: { enabled: false }, color: 'red', draggableY: true, data: [] }] }); } /*, function(chart) { // on complete chart.series[2].legendItem.attr('text', 'Good Luck!'); chart.legend.render(); } );*/ ///// INITATE FUNCTIONS getDataJson(); getDataJson(); getDataJson(); getDataJson(); getDataJson(); /*getDataJson();getDataJson();getDataJson();getDataJson();getDataJson();*/ getScore(); ///// update chart function chartUpdate() { //alert("entering"); displayIx == 14 ? displayIx = 1 : displayIx++; index = displayIx; //console.log(index+" index "); //FLAG TOGGLE stuck = false; if (a2Ix != undefined) { //CHART FUNCTIONS if (a2Ix[index].length > 10) { TEMPiNDEX = index; chart.series[0].setData(eval("[]")); chart.series[1].setData(eval("[]")); chart.series[2].setData(eval("[]")); if (!singlePoint) { chart.series[3].setData(eval("[]")); chart.series[4].setData(eval("[]")); var pointValY = a2Ix[index][dataPointsInit - 2][4] + 0.10; var pointValY2 = a2Ix[index][dataPointsInit - 2][4] - 0.10; chart.series[3].addPoint([1, pointValY], true); chart.series[3].addPoint([299, pointValY], true); chart.series[4].addPoint([1, pointValY2], true); chart.series[4].addPoint([299, pointValY2], true); } chart.yAxis[0].setExtremes(null, null); var d1 = "[ [" + a2Ix[index].join(" ], [ ") + "] ]"; var d2 = "[ [" + a3Ix[index].join(" ], [ ") + "] ]"; chart.series[1].setData(eval(d1)); chart.series[2].setData(eval(d2)); chart.series[1].hide(); chart.series[2].show(); } } //console.log("TEMPiNDEX "+TEMPiNDEX+"index "+index); } ///// end of chart update ///// get data function getDataJson() { var originalDataIx = ""; new Date().toString(); $.ajax({ url: '/dataFiles/minuteData/datacsv.php', //the script to call to get data data: "", //you can insert url argumnets here to pass to api.php cache: false, success: function (data) { retrieveIx == 14 ? retrieveIx = 1 : retrieveIx++; if (data.charAt(0) == '[') { originalDataIx = data; a2Ix[retrieveIx] = $.parseJSON(originalDataIx); a3Ix[retrieveIx] = $.parseJSON(originalDataIx); maxDIx[retrieveIx] = 0, minDIx[retrieveIx] = 9999999, lastDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][dataPointsInit][4]); dailyVolIx[retrieveIx] = 0; sumPriceIx[retrieveIx] = 0; for (var i = 0; i < a2Ix[retrieveIx].length; i++) { if (maxDIx[retrieveIx] < parseFloat(a2Ix[retrieveIx][i][2])) { maxDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][i][2]); } if (minDIx[retrieveIx] > parseFloat(a2Ix[retrieveIx][i][3])) { minDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][i][3]); } } for (var i = 0; i < a2Ix[retrieveIx].length; i++) { a2Ix[retrieveIx][i][1] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][1]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][2] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][2]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][3] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][3]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][4] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][4]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); if (i != 0) dailyVolIx[retrieveIx] = dailyVolIx[retrieveIx] + Math.abs(a2Ix[retrieveIx][i][4] - a2Ix[retrieveIx][i - 1][4]); sumPriceIx[retrieveIx] = sumPriceIx[retrieveIx] + a2Ix[retrieveIx][i][1]; if (i > dataPointsInit) { a3Ix[retrieveIx][i][0] = i + 1; a3Ix[retrieveIx][i][1] = "'-'"; a3Ix[retrieveIx][i][2] = "'-'"; a3Ix[retrieveIx][i][3] = "'-'"; a3Ix[retrieveIx][i][4] = "'-'"; } else { a3Ix[retrieveIx][i][0] = i + 1; a3Ix[retrieveIx][i][1] = a2Ix[retrieveIx][i][1]; a3Ix[retrieveIx][i][2] = a2Ix[retrieveIx][i][2]; a3Ix[retrieveIx][i][3] = a2Ix[retrieveIx][i][3]; a3Ix[retrieveIx][i][4] = a2Ix[retrieveIx][i][4]; } } dailyVolIx[retrieveIx] = dailyVolIx[retrieveIx] / i; if (firstChart == true) { //alert("yipee"); firstChart = false; //chart.hideLoading(); createChart(); chartUpdate(); } } else { a2Ix[retrieveIx] = ""; a3Ix[retrieveIx] = ""; //console.log("Error in data recieved: "+ data); } //console.log("data recieved "+retrieveIx); }, error: function (jqXHR, exception) { //console.log("Error in getting Data. Sorry for the issue. Please come back later."); a2Ix[retrieveIx] = ""; a3Ix[retrieveIx] = ""; } }); } /////end of get data //// start of get score function getScore() { $.ajax({ url: '/dataFiles/minuteData/getUserScore.php', //the script to call to get data data: "", //you can insert url argumnets here to pass to api.php cache: false, success: function (data) { playerScore = data.split('#'); if (playerScore != null) { averageScore[0] = parseFloat(playerScore[0]); countScore[0] = parseFloat(playerScore[1]); percentScore[0] = parseFloat(playerScore[2]); updateDisplayScore(averageScore[0].toFixed(2) + " pts " + countScore[0] + " plays", 0, 2); averageScore[1] = parseFloat(playerScore[3]); countScore[1] = parseFloat(playerScore[4]); percentScore[1] = parseFloat(playerScore[5]); updateDisplayScore(averageScore[1].toFixed(2) + " pts " + countScore[1] + " plays", 1, 2); } } }); } //// end of get score //TOOL BAR FUNCTIONS BELOW NOTHING TO DO WITH CHART if (firstChart == true) { // chart.showLoading(); } jQuery("#submitChart").button({ text: true, icons: { primary: "ui-icon-circle-check" } }) .click(function () { if (!singlePoint) { if (!stuck) { chart.series[1].show(); chart.series[2].hide(); var p = chart.series[3].points[0].y; var q = chart.series[4].points[0].y; if ((a2Ix[displayIx][dataPointsInit - 1][4] - p) * (a2Ix[displayIx][dataPointsInit - 1][4] - q) > 0) { alert("SL and TP cannot be on same side."); return; } var shortSell = -1; var target = 0; if (p < q) shortSell = 1; if (shortSell == -1) { for (var j = dataPointsInit; ((j < dataPoints) + (target == 0)) == 2; j++) { if (a2Ix[displayIx][j][2] > p) target = 1; if (a2Ix[displayIx][j][3] < q) target = -1; } } else { for (var j = dataPointsInit; ((j < dataPoints) + (target == 0)) == 2; j++) { if (a2Ix[displayIx][j][3] < p) target = 1; if (a2Ix[displayIx][j][2] > q) target = -1; } } if (target == 0) minDist = (a2Ix[displayIx][dataPointsInit - 1][4] - a2Ix[displayIx][dataPoints - 1][4]) * (shortSell); if (target == 1) minDist = Math.abs(p - a2Ix[displayIx][dataPointsInit - 1][4]); if (target == -1) minDist = Math.abs(q - a2Ix[displayIx][dataPointsInit - 1][4]) * (-1); $.ajax({ type: 'GET', url: '/dataFiles/minuteData/updateMinuteAndGetData.php', data: { dataString: minDist.toFixed(2), typeString: 2 }, success: function (dataResponse) { retrieveIx == 14 ? retrieveIx = 1 : retrieveIx++; if (dataResponse.charAt(0) == '[') { originalDataIx = dataResponse; a2Ix[retrieveIx] = $.parseJSON(originalDataIx); a3Ix[retrieveIx] = $.parseJSON(originalDataIx); maxDIx[retrieveIx] = 0, minDIx[retrieveIx] = 9999999, lastDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][dataPointsInit][4]); dailyVolIx[retrieveIx] = 0; sumPriceIx[retrieveIx] = 0; for (var i = 0; i < a2Ix[retrieveIx].length; i++) { if (maxDIx[retrieveIx] < parseFloat(a2Ix[retrieveIx][i][2])) { maxDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][i][2]); } if (minDIx[retrieveIx] > parseFloat(a2Ix[retrieveIx][i][3])) { minDIx[retrieveIx] = parseFloat(a2Ix[retrieveIx][i][3]); } } for (var i = 0; i < a2Ix[retrieveIx].length; i++) { a2Ix[retrieveIx][i][1] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][1]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][2] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][2]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][3] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][3]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); a2Ix[retrieveIx][i][4] = (maxDIx[retrieveIx] - a2Ix[retrieveIx][i][4]) / (maxDIx[retrieveIx] - minDIx[retrieveIx]); if (i != 0) dailyVolIx[retrieveIx] = dailyVolIx[retrieveIx] + Math.abs(a2Ix[retrieveIx][i][4] - a2Ix[retrieveIx][i - 1][4]); sumPriceIx[retrieveIx] = sumPriceIx[retrieveIx] + a2Ix[retrieveIx][i][1]; if (i > dataPointsInit) { a3Ix[retrieveIx][i][0] = i + 1; a3Ix[retrieveIx][i][1] = "'-'"; a3Ix[retrieveIx][i][2] = "'-'"; a3Ix[retrieveIx][i][3] = "'-'"; a3Ix[retrieveIx][i][4] = "'-'"; } else { a3Ix[retrieveIx][i][0] = i + 1; a3Ix[retrieveIx][i][1] = a2Ix[retrieveIx][i][1]; a3Ix[retrieveIx][i][2] = a2Ix[retrieveIx][i][2]; a3Ix[retrieveIx][i][3] = a2Ix[retrieveIx][i][3]; a3Ix[retrieveIx][i][4] = a2Ix[retrieveIx][i][4]; } } dailyVolIx[retrieveIx] = dailyVolIx[retrieveIx] / i; if (firstChart == true) { //alert("yipee"); firstChart = false; //chart.hideLoading(); createChart(); chartUpdate(); } } else { a2Ix[retrieveIx] = ""; a3Ix[retrieveIx] = ""; //console.log("Error in data recieved: "+ data); } //console.log("data recieved "+retrieveIx); }, error: function (jqXHR, exception) { //console.log("Error in getting Data. Sorry for the issue. Please come back later."); a2Ix[retrieveIx] = ""; a3Ix[retrieveIx] = ""; } }); score.push(minDist); sessionCount[1]++; sessionScore[1] = sessionScore[1] + minDist; sessionAvg[1] = sessionScore[1] / sessionCount[1]; totalCount[1] = (countScore[1] + sessionCount[1]); totalScore[1] = (parseInt(averageScore[1]) * countScore[1] + sessionScore[1]) / totalCount[1]; updateDisplayScore(minDist.toFixed(2) + " points", 1, 0); updateDisplayScore(sessionScore[1].toFixed(2) + " pts " + sessionCount[1] + " plays", 1, 1); updateDisplayScore(totalScore[1].toFixed(2) + " pts " + totalCount[1] + " plays", 1, 2); stuck = true; jQuery("#submitChart").hide(); jQuery("#nextChart").show(); /* nextImage.show(); finshedImage.hide(); */ } } }); jQuery("#submitChart").hide(); jQuery("#scrollUp").button({ text: false, icons: { primary: "ui-icon-circle-triangle-n" } }) .click(function () { var yData = chart.yAxis[0].getExtremes(); chart.yAxis[0].setExtremes((yData.min + chart.yAxis[0].tickInterval), (yData.max + chart.yAxis[0].tickInterval)); }); jQuery("#scrollDn").button({ text: false, icons: { primary: "ui-icon-circle-triangle-s" } }) .on('click', function () { var yData = chart.yAxis[0].getExtremes(); chart.yAxis[0].setExtremes((yData.min - chart.yAxis[0].tickInterval), (yData.max - chart.yAxis[0].tickInterval)); }); jQuery("#nextChart").button({ text: true, icons: { primary: "ui-icon-circle-arrow-e" } }) .click(function () { if (stuck) { chart.tooltip.hide(); while (((displayIx >= retrieveIx) + retrieveIx != 1) == 2) { alert("Please click again as either your network is currently slow or our servers are facing heavy load"); } chartUpdate(); getDataJson(); if (!singlePoint) { jQuery("#submitChart").show(); jQuery("#nextChart").hide(); /* finshedImage.show(); nextImage.hide(); */ } stuck = false; } }); jQuery("#scoreHead").button(); jQuery("#scoreText").button(); jQuery("#contactus").button({ text: false, icons: { primary: "ui-icon-mail-closed" } }); jQuery("#logoutin").button({ text: false, icons: { primary: "ui-icon-locked" } }); jQuery("#facebook").button({ text: false, icons: { primary: "sy-icon-fb" } }); jQuery("#playhelp").button({ text: false, icons: { primary: "ui-icon-help" } }) .click(function () { showHelp = !showHelp; if (!showHelp) jQuery(".highcharts-tooltip").css('display', 'none'); if (showHelp) jQuery(".highcharts-tooltip").css('display', 'block'); }); jQuery("#scoreHead")[0].gameChoice = 0; jQuery("#scoreHead")[0].tenorChoice = 0; jQuery("#scoreHead").button() .click(function () { var options; if ($(this).text() === "One: Predict") { $(this).html('<span class="ui-button-text">Two: Trade</span>'); $(this)[0].gameChoice = 1; updateDisplayForm(parseInt(jQuery("#scoreHead")[0].gameChoice), jQuery("#scoreHead")[0].tenorChoice); } else { $(this).html('<span class="ui-button-text">One: Predict</span>'); $(this)[0].gameChoice = 0; updateDisplayForm(parseInt(jQuery("#scoreHead")[0].gameChoice), jQuery("#scoreHead")[0].tenorChoice); } }); jQuery("#next").button({ text: false, icons: { primary: "ui-icon-play" } }); jQuery("#repeat").buttonset(); jQuery("#repeat0") .click(function () { jQuery("#scoreHead")[0].tenorChoice = 0; updateDisplayForm(parseInt(jQuery("#scoreHead")[0].gameChoice), 0); }); jQuery("#repeat1") .click(function () { jQuery("#scoreHead")[0].tenorChoice = 1; updateDisplayForm(parseInt(jQuery("#scoreHead")[0].gameChoice), 1); }); jQuery("#repeatall") .click(function () { jQuery("#scoreHead")[0].tenorChoice = 2; updateDisplayForm(parseInt(jQuery("#scoreHead")[0].gameChoice), 2); }); function updateDisplayScore(a, b, c) { displayScore[b][c] = a; if (parseInt(jQuery("#scoreHead")[0].gameChoice) == b) { if (jQuery("#scoreHead")[0].tenorChoice == (c)) { updateDisplayForm(b, c); } } } function updateDisplayForm(b, c) { jQuery("#scoreText").html('<span class="ui-button-text">' + displayScore[b][c] + '</span>'); } /////// }); })(jQuery); jQuery(document).ready(function () { jQuery(".sy-header").equalHeights(); jQuery(function () { jQuery(".slideshow").show(); }); jQuery('.show_hide').showHide({ speed: 1000, // speed you want the toggle to happen easing: '', // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI changeText: 1, // if you dont want the button text to change, set this to 0 showText: 'Click here to view more information', // the button text to show when a div is closed hideText: 'Click here to view less information' // the button text to show when a div is open }); }); (function ($) { $.fn.showHide = function (options) { var defaults = { speed: 1000, easing: '', changeText: 0, showText: 'Show', hideText: 'Hide' }; var options = $.extend(defaults, options); $(this).click(function () { $('.toggleDiv').slideUp(options.speed, options.easing); var toggleClick = $(this); var toggleDiv = $(this).attr('rel'); $(toggleDiv).slideToggle(options.speed, options.easing, function () { if (options.changeText == 1) { $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); } }); return false; }); }; })(jQuery);
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Shows the desired contents of the tape. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Target'); goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.sprites.numberplate'); goog.require('turing.util'); /** * The left offset of the target number plate. * @type {string} * @const */ turing.NUMBER_PLATE_LEFT = '280px'; /** * The top offset of the target number plate. * @type {string} * @const */ turing.NUMBER_PLATE_TOP = '21px'; /** * The top offset of the track from the tape to the target number plate. * @type {string} * @const */ turing.TRACK_TO_NUMBER_PLATE_TOP = '40px'; /** * The left offset of the track from the tape to the target number plate. * @type {string} * @const */ turing.TRACK_TO_NUMBER_PLATE_LEFT = '383px'; /** * The top offset of the equal indicator. * @type {string} * @const */ turing.EQUAL_INDICATOR_TOP = '25px'; /** * The left offset of the equal indicator. * @type {string} * @const */ turing.EQUAL_INDICATOR_LEFT = '411px'; /** * The amount of time it takes to blink the equal sign once. * @type {number} * @const */ turing.EQUAL_BLINK_DURATION = 400; /** * A plate showing the desired state of the tape. * @constructor */ turing.Target = function() { /** * Div for the plate with numbers the user is trying to match. * @type {Element} * @private */ this.numberPlate_; /** * The current value of the target number plate. * @type {string} * @private */ this.curValue_ = ''; /** * A track segment leading from the tape to the target number plate. * @type {Element} * @private */ this.trackToNumberPlate_; /** * The equivalence indicator shown on the track segment that leads to the * number plate. * @type {Element} * @private */ this.equalIndicator_; /** * A click event listener bound on the equals indicator. * @type {Function} * @private */ this.equalClickListener_; /** * A callback called when the equals indicator is clicked. * @type {?function()} * @private */ this.equalClickCallback_; }; /** * Creates dom nodes. */ turing.Target.prototype.create = function() { this.numberPlate_ = turing.sprites.getDiv('target-blank'); this.numberPlate_.style.top = turing.NUMBER_PLATE_TOP; this.numberPlate_.style.zIndex = 400; this.numberPlate_.style.left = turing.NUMBER_PLATE_LEFT; this.trackToNumberPlate_ = turing.sprites.getDiv('track'); var trackToNumberPlateStyle = this.trackToNumberPlate_.style; trackToNumberPlateStyle.top = turing.TRACK_TO_NUMBER_PLATE_TOP; trackToNumberPlateStyle.left = turing.TRACK_TO_NUMBER_PLATE_LEFT; // We're repurposing the track icon but only showing a small part of it. trackToNumberPlateStyle.height = '9px'; trackToNumberPlateStyle.width = '40px'; trackToNumberPlateStyle.zIndex = 398; // Behind tape and number plate. this.equalIndicator_ = turing.sprites.getDiv('eq-dim'); this.equalIndicator_.style.top = turing.EQUAL_INDICATOR_TOP; this.equalIndicator_.style.left = turing.EQUAL_INDICATOR_LEFT; this.equalIndicator_.style.zIndex = 399; // Above trackToNumberPlate. this.equalClickListener_ = goog.bind(this.onClickEqual_, this); turing.util.listen(this.equalIndicator_, 'click', this.equalClickListener_); }; /** * Cleans up dom nodes. */ turing.Target.prototype.destroy = function() { turing.util.removeNode(this.numberPlate_); this.numberPlate_ = null; turing.util.removeNode(this.trackToNumberPlate_); this.trackToNumberPlate_ = null; turing.util.unlisten(this.equalIndicator_, 'click', this.equalClickListener_); this.equalClickListener_ = null; turing.util.removeNode(this.equalIndicator_); this.equalIndicator_ = null; this.curValue_ = ''; }; /** * Attaches dom nodes. * @param {Element} elem Where to attach. */ turing.Target.prototype.attachTo = function(elem) { elem.appendChild(this.numberPlate_); elem.appendChild(this.trackToNumberPlate_); elem.appendChild(this.equalIndicator_); }; /** * Sets the value on the target number plate. * @param {string} str The desired bit string, or the empty string for a blank * target. * @param {number} duration The amount of time to animate for. */ turing.Target.prototype.setValue = function(str, duration) { if (!str && !this.curValue_) { // Don't switch sheets! It causes flashing! So just pick the first // blank target in the deferred sheet. this.numberPlate_.style.background = turing.sprites.getBackground( 'scroll-01011-18'); return; } var backgrounds; if (!str) { // We're switching to blank so animate the current value scrolling away. backgrounds = turing.sprites.numberplate.getScrollingTarget( this.curValue_, false); } else { // We're switching to the given string, so animate it scrolling in. backgrounds = turing.sprites.numberplate.getScrollingTarget(str, true); } if (!duration) { this.numberPlate_.style.background = backgrounds[backgrounds.length - 1]; } else { turing.anim.animateThroughBackgrounds( this.numberPlate_, backgrounds, duration); } this.curValue_ = str; }; /** * Sets the equal indicator. * @param {string} str One of 'dim', 'eq', or 'neq'. * @param {number=} opt_blinkDelay If specified, the amount of time to blink * the equal display. */ turing.Target.prototype.setEqual = function(str, opt_blinkDelay) { if (!opt_blinkDelay || opt_blinkDelay < turing.EQUAL_BLINK_DURATION) { this.equalIndicator_.style.background = turing.sprites.getBackground( 'eq-' + str); } else { var backgrounds = []; var remainingDelay = opt_blinkDelay; while (remainingDelay > turing.EQUAL_BLINK_DURATION) { backgrounds.push('eq-dim'); backgrounds.push('eq-' + str); remainingDelay = remainingDelay - turing.EQUAL_BLINK_DURATION; } backgrounds.push('eq-dim'); turing.anim.animateFromSprites( this.equalIndicator_, backgrounds, opt_blinkDelay); } }; /** * Highlights the given space on the number plate. * @param {string} str The desired bit string. * @param {number} index The index of the number to highlight, or 5 which is * the length of the target, to highlight the entire number plate. * @param {number} duration The amount of time to highlight for. */ turing.Target.prototype.highlightAt = function(str, index, duration) { if (index > str.length) { return; } var lowlit = turing.sprites.numberplate.getLitTargetForDigit( str, index, false); var lit = turing.sprites.numberplate.getLitTargetForDigit( str, index, true); var unlit = turing.sprites.numberplate.getUnlitNumberPlate(str); turing.anim.animateThroughBackgrounds(this.numberPlate_, [unlit, lowlit, lit, lit, lit, lit, lowlit, unlit], duration); }; /** * Pops up a bunny in the equals indicator and makes it clickable. * @param {function()} onClick Callback to call when clicked. * @param {string} color The color for the bunny background. */ turing.Target.prototype.showBonusBunny = function(onClick, color) { this.setEqual('bunny-' + color); this.equalIndicator_.style.cursor = 'pointer'; this.equalClickCallback_ = onClick; }; /** * Click handler for the equal indicator. * @private */ turing.Target.prototype.onClickEqual_ = function() { if (this.equalClickCallback_) { this.equalClickCallback_(); } }; /** * Hides the bunny in the equals indicator and makes it non-clickable. */ turing.Target.prototype.hideBonusBunny = function() { this.equalClickCallback_ = null; this.equalIndicator_.style.cursor = 'default'; this.setEqual('dim'); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Offsets for sprites. Auto-generated; do not edit. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.sprites.offsets'); /** * Sprite bounding box inside a combined image. * @typedef {{x: number, y: number, width: number, height: number}} */ turing.sprites.offsets.Rect; /** * Bounding boxes of sprites in combined image. * @type {Object.<string, turing.sprites.offsets.Rect>} */ turing.sprites.offsets.RECTS = { 'G0': {x: 0, y: 613, width: 35, height: 37}, 'G1': {x: 35, y: 613, width: 35, height: 37}, 'G2': {x: 70, y: 613, width: 35, height: 37}, 'G3': {x: 105, y: 613, width: 35, height: 37}, 'G4': {x: 140, y: 613, width: 35, height: 37}, 'G5': {x: 175, y: 613, width: 35, height: 37}, 'G6': {x: 210, y: 613, width: 35, height: 37}, 'G7': {x: 245, y: 613, width: 35, height: 37}, 'e0': {x: 0, y: 653, width: 22, height: 23}, 'e1': {x: 22, y: 653, width: 22, height: 23}, 'e2': {x: 44, y: 653, width: 22, height: 23}, 'e3': {x: 66, y: 653, width: 22, height: 23}, 'e4': {x: 88, y: 653, width: 22, height: 23}, 'e5': {x: 110, y: 653, width: 22, height: 23}, 'e6': {x: 132, y: 653, width: 22, height: 23}, 'e7': {x: 154, y: 653, width: 22, height: 23}, 'eq-bunny-b': {x: 137, y: 0, width: 40, height: 40}, 'eq-bunny-g': {x: 217, y: 0, width: 40, height: 40}, 'eq-bunny-r': {x: 257, y: 0, width: 40, height: 40}, 'eq-bunny-y': {x: 177, y: 0, width: 40, height: 40}, 'eq-dim': {x: 97, y: 0, width: 40, height: 40}, 'eq-eq': {x: 337, y: 0, width: 40, height: 40}, 'eq-neq': {x: 297, y: 0, width: 40, height: 40}, 'g0': {x: 366, y: 640, width: 26, height: 36}, 'g1': {x: 392, y: 640, width: 26, height: 36}, 'g2': {x: 418, y: 640, width: 26, height: 36}, 'g3': {x: 444, y: 640, width: 26, height: 36}, 'g4': {x: 470, y: 640, width: 26, height: 36}, 'g5': {x: 496, y: 640, width: 26, height: 36}, 'g6': {x: 522, y: 640, width: 26, height: 36}, 'g7': {x: 548, y: 640, width: 26, height: 36}, 'head': {x: 286, y: 554, width: 61, height: 59}, 'l0': {x: 380, y: 0, width: 16, height: 35}, 'l1': {x: 396, y: 0, width: 16, height: 35}, 'l2': {x: 412, y: 0, width: 16, height: 35}, 'l3': {x: 428, y: 0, width: 16, height: 35}, 'l4': {x: 444, y: 0, width: 16, height: 35}, 'l5': {x: 460, y: 0, width: 16, height: 35}, 'l6': {x: 476, y: 0, width: 16, height: 35}, 'l7': {x: 492, y: 0, width: 16, height: 35}, 'o-back-i': {x: 665, y: 416, width: 35, height: 45}, 'o-back-i-in': {x: 665, y: 506, width: 35, height: 45}, 'o-back-i-lit': {x: 665, y: 461, width: 35, height: 45}, 'o-back-i-out': {x: 665, y: 326, width: 35, height: 45}, 'o-back-i-out-lit': {x: 665, y: 371, width: 35, height: 45}, 'o-back-s': {x: 714, y: 48, width: 34, height: 45}, 'o-back-s-lit-b': {x: 714, y: 138, width: 34, height: 45}, 'o-back-s-lit-g': {x: 714, y: 228, width: 34, height: 45}, 'o-back-s-lit-r': {x: 714, y: 183, width: 34, height: 45}, 'o-back-s-lit-y': {x: 714, y: 93, width: 34, height: 45}, 'o-back2-i': {x: 385, y: 416, width: 35, height: 45}, 'o-back2-i-in': {x: 385, y: 506, width: 35, height: 45}, 'o-back2-i-lit': {x: 385, y: 461, width: 35, height: 45}, 'o-back2-i-out': {x: 385, y: 326, width: 35, height: 45}, 'o-back2-i-out-lit': {x: 385, y: 371, width: 35, height: 45}, 'o-back2-s': {x: 442, y: 48, width: 34, height: 45}, 'o-back2-s-lit-b': {x: 442, y: 138, width: 34, height: 45}, 'o-back2-s-lit-g': {x: 442, y: 228, width: 34, height: 45}, 'o-back2-s-lit-r': {x: 442, y: 183, width: 34, height: 45}, 'o-back2-s-lit-y': {x: 442, y: 93, width: 34, height: 45}, 'o-back3-i': {x: 420, y: 416, width: 35, height: 45}, 'o-back3-i-in': {x: 420, y: 506, width: 35, height: 45}, 'o-back3-i-lit': {x: 420, y: 461, width: 35, height: 45}, 'o-back3-i-out': {x: 420, y: 326, width: 35, height: 45}, 'o-back3-i-out-lit': {x: 420, y: 371, width: 35, height: 45}, 'o-back3-s': {x: 476, y: 48, width: 34, height: 45}, 'o-back3-s-lit-b': {x: 476, y: 138, width: 34, height: 45}, 'o-back3-s-lit-g': {x: 476, y: 228, width: 34, height: 45}, 'o-back3-s-lit-r': {x: 476, y: 183, width: 34, height: 45}, 'o-back3-s-lit-y': {x: 476, y: 93, width: 34, height: 45}, 'o-back4-i': {x: 455, y: 416, width: 35, height: 45}, 'o-back4-i-in': {x: 455, y: 506, width: 35, height: 45}, 'o-back4-i-lit': {x: 455, y: 461, width: 35, height: 45}, 'o-back4-i-out': {x: 455, y: 326, width: 35, height: 45}, 'o-back4-i-out-lit': {x: 455, y: 371, width: 35, height: 45}, 'o-back4-s': {x: 510, y: 48, width: 34, height: 45}, 'o-back4-s-lit-b': {x: 510, y: 138, width: 34, height: 45}, 'o-back4-s-lit-g': {x: 510, y: 228, width: 34, height: 45}, 'o-back4-s-lit-r': {x: 510, y: 183, width: 34, height: 45}, 'o-back4-s-lit-y': {x: 510, y: 93, width: 34, height: 45}, 'o-back8-i': {x: 595, y: 416, width: 35, height: 45}, 'o-back8-i-in': {x: 595, y: 506, width: 35, height: 45}, 'o-back8-i-lit': {x: 595, y: 461, width: 35, height: 45}, 'o-back8-i-out': {x: 595, y: 326, width: 35, height: 45}, 'o-back8-i-out-lit': {x: 595, y: 371, width: 35, height: 45}, 'o-back8-s': {x: 646, y: 48, width: 34, height: 45}, 'o-back8-s-lit-b': {x: 646, y: 138, width: 34, height: 45}, 'o-back8-s-lit-g': {x: 646, y: 228, width: 34, height: 45}, 'o-back8-s-lit-r': {x: 646, y: 183, width: 34, height: 45}, 'o-back8-s-lit-y': {x: 646, y: 93, width: 34, height: 45}, 'o-back9-i': {x: 630, y: 416, width: 35, height: 45}, 'o-back9-i-in': {x: 630, y: 506, width: 35, height: 45}, 'o-back9-i-lit': {x: 630, y: 461, width: 35, height: 45}, 'o-back9-i-out': {x: 630, y: 326, width: 35, height: 45}, 'o-back9-i-out-lit': {x: 630, y: 371, width: 35, height: 45}, 'o-back9-s': {x: 680, y: 48, width: 34, height: 45}, 'o-back9-s-lit-b': {x: 680, y: 138, width: 34, height: 45}, 'o-back9-s-lit-g': {x: 680, y: 228, width: 34, height: 45}, 'o-back9-s-lit-r': {x: 680, y: 183, width: 34, height: 45}, 'o-back9-s-lit-y': {x: 680, y: 93, width: 34, height: 45}, 'o-blank-down-i': {x: 735, y: 416, width: 35, height: 45}, 'o-blank-down-i-in': {x: 735, y: 506, width: 35, height: 45}, 'o-blank-down-i-lit': {x: 735, y: 461, width: 35, height: 45}, 'o-blank-down-i-out': {x: 735, y: 326, width: 35, height: 45}, 'o-blank-down-i-out-lit': {x: 735, y: 371, width: 35, height: 45}, 'o-blank-down-s': {x: 782, y: 48, width: 34, height: 45}, 'o-blank-down-s-lit-b': {x: 782, y: 138, width: 34, height: 45}, 'o-blank-down-s-lit-g': {x: 782, y: 228, width: 34, height: 45}, 'o-blank-down-s-lit-r': {x: 782, y: 183, width: 34, height: 45}, 'o-blank-down-s-lit-y': {x: 782, y: 93, width: 34, height: 45}, 'o-blank-i': {x: 0, y: 416, width: 35, height: 45}, 'o-blank-i-in': {x: 0, y: 506, width: 35, height: 45}, 'o-blank-i-lit': {x: 0, y: 461, width: 35, height: 45}, 'o-blank-i-out': {x: 0, y: 326, width: 35, height: 45}, 'o-blank-i-out-lit': {x: 0, y: 371, width: 35, height: 45}, 'o-blank-s': {x: 34, y: 48, width: 34, height: 45}, 'o-blank-s-lit-b': {x: 34, y: 138, width: 34, height: 45}, 'o-blank-s-lit-g': {x: 34, y: 228, width: 34, height: 45}, 'o-blank-s-lit-r': {x: 34, y: 183, width: 34, height: 45}, 'o-blank-s-lit-y': {x: 34, y: 93, width: 34, height: 45}, 'o-blank-up-i': {x: 700, y: 416, width: 35, height: 45}, 'o-blank-up-i-in': {x: 700, y: 506, width: 35, height: 45}, 'o-blank-up-i-lit': {x: 700, y: 461, width: 35, height: 45}, 'o-blank-up-i-out': {x: 700, y: 326, width: 35, height: 45}, 'o-blank-up-i-out-lit': {x: 700, y: 371, width: 35, height: 45}, 'o-blank-up-s': {x: 748, y: 48, width: 34, height: 45}, 'o-blank-up-s-lit-b': {x: 748, y: 138, width: 34, height: 45}, 'o-blank-up-s-lit-g': {x: 748, y: 228, width: 34, height: 45}, 'o-blank-up-s-lit-r': {x: 748, y: 183, width: 34, height: 45}, 'o-blank-up-s-lit-y': {x: 748, y: 93, width: 34, height: 45}, 'o-dim-s': {x: 0, y: 48, width: 34, height: 45}, 'o-dim-s-lit-b': {x: 0, y: 138, width: 34, height: 45}, 'o-dim-s-lit-g': {x: 0, y: 228, width: 34, height: 45}, 'o-dim-s-lit-r': {x: 0, y: 183, width: 34, height: 45}, 'o-dim-s-lit-y': {x: 0, y: 93, width: 34, height: 45}, 'o-down0-i': {x: 35, y: 416, width: 35, height: 45}, 'o-down0-i-in': {x: 35, y: 506, width: 35, height: 45}, 'o-down0-i-lit': {x: 35, y: 461, width: 35, height: 45}, 'o-down0-i-out': {x: 35, y: 326, width: 35, height: 45}, 'o-down0-i-out-lit': {x: 35, y: 371, width: 35, height: 45}, 'o-down0-s': {x: 102, y: 48, width: 34, height: 45}, 'o-down0-s-lit-b': {x: 102, y: 138, width: 34, height: 45}, 'o-down0-s-lit-g': {x: 102, y: 228, width: 34, height: 45}, 'o-down0-s-lit-r': {x: 102, y: 183, width: 34, height: 45}, 'o-down0-s-lit-y': {x: 102, y: 93, width: 34, height: 45}, 'o-down1-i': {x: 70, y: 416, width: 35, height: 45}, 'o-down1-i-in': {x: 70, y: 506, width: 35, height: 45}, 'o-down1-i-lit': {x: 70, y: 461, width: 35, height: 45}, 'o-down1-i-out': {x: 70, y: 326, width: 35, height: 45}, 'o-down1-i-out-lit': {x: 70, y: 371, width: 35, height: 45}, 'o-down1-s': {x: 136, y: 48, width: 34, height: 45}, 'o-down1-s-lit-b': {x: 136, y: 138, width: 34, height: 45}, 'o-down1-s-lit-g': {x: 136, y: 228, width: 34, height: 45}, 'o-down1-s-lit-r': {x: 136, y: 183, width: 34, height: 45}, 'o-down1-s-lit-y': {x: 136, y: 93, width: 34, height: 45}, 'o-down_-i': {x: 105, y: 416, width: 35, height: 45}, 'o-down_-i-in': {x: 105, y: 506, width: 35, height: 45}, 'o-down_-i-lit': {x: 105, y: 461, width: 35, height: 45}, 'o-down_-i-out': {x: 105, y: 326, width: 35, height: 45}, 'o-down_-i-out-lit': {x: 105, y: 371, width: 35, height: 45}, 'o-down_-s': {x: 170, y: 48, width: 34, height: 45}, 'o-down_-s-lit-b': {x: 170, y: 138, width: 34, height: 45}, 'o-down_-s-lit-g': {x: 170, y: 228, width: 34, height: 45}, 'o-down_-s-lit-r': {x: 170, y: 183, width: 34, height: 45}, 'o-down_-s-lit-y': {x: 170, y: 93, width: 34, height: 45}, 'o-left-i': {x: 280, y: 416, width: 35, height: 45}, 'o-left-i-in': {x: 280, y: 506, width: 35, height: 45}, 'o-left-i-lit': {x: 280, y: 461, width: 35, height: 45}, 'o-left-i-out': {x: 280, y: 326, width: 35, height: 45}, 'o-left-i-out-lit': {x: 280, y: 371, width: 35, height: 45}, 'o-left-s': {x: 340, y: 48, width: 34, height: 45}, 'o-left-s-lit-b': {x: 340, y: 138, width: 34, height: 45}, 'o-left-s-lit-g': {x: 340, y: 228, width: 34, height: 45}, 'o-left-s-lit-r': {x: 340, y: 183, width: 34, height: 45}, 'o-left-s-lit-y': {x: 340, y: 93, width: 34, height: 45}, 'o-print0-i': {x: 350, y: 416, width: 35, height: 45}, 'o-print0-i-in': {x: 350, y: 506, width: 35, height: 45}, 'o-print0-i-lit': {x: 350, y: 461, width: 35, height: 45}, 'o-print0-i-out': {x: 350, y: 326, width: 35, height: 45}, 'o-print0-i-out-lit': {x: 350, y: 371, width: 35, height: 45}, 'o-print0-s': {x: 408, y: 48, width: 34, height: 45}, 'o-print0-s-lit-b': {x: 408, y: 138, width: 34, height: 45}, 'o-print0-s-lit-g': {x: 408, y: 228, width: 34, height: 45}, 'o-print0-s-lit-r': {x: 408, y: 183, width: 34, height: 45}, 'o-print0-s-lit-y': {x: 408, y: 93, width: 34, height: 45}, 'o-print1-i': {x: 315, y: 416, width: 35, height: 45}, 'o-print1-i-in': {x: 315, y: 506, width: 35, height: 45}, 'o-print1-i-lit': {x: 315, y: 461, width: 35, height: 45}, 'o-print1-i-out': {x: 315, y: 326, width: 35, height: 45}, 'o-print1-i-out-lit': {x: 315, y: 371, width: 35, height: 45}, 'o-print1-s': {x: 374, y: 48, width: 34, height: 45}, 'o-print1-s-lit-b': {x: 374, y: 138, width: 34, height: 45}, 'o-print1-s-lit-g': {x: 374, y: 228, width: 34, height: 45}, 'o-print1-s-lit-r': {x: 374, y: 183, width: 34, height: 45}, 'o-print1-s-lit-y': {x: 374, y: 93, width: 34, height: 45}, 'o-rback2-i': {x: 490, y: 416, width: 35, height: 45}, 'o-rback2-i-in': {x: 490, y: 506, width: 35, height: 45}, 'o-rback2-i-lit': {x: 490, y: 461, width: 35, height: 45}, 'o-rback2-i-out': {x: 490, y: 326, width: 35, height: 45}, 'o-rback2-i-out-lit': {x: 490, y: 371, width: 35, height: 45}, 'o-rback2-s': {x: 544, y: 48, width: 34, height: 45}, 'o-rback2-s-lit-b': {x: 544, y: 138, width: 34, height: 45}, 'o-rback2-s-lit-g': {x: 544, y: 228, width: 34, height: 45}, 'o-rback2-s-lit-r': {x: 544, y: 183, width: 34, height: 45}, 'o-rback2-s-lit-y': {x: 544, y: 93, width: 34, height: 45}, 'o-rback3-i': {x: 525, y: 416, width: 35, height: 45}, 'o-rback3-i-in': {x: 525, y: 506, width: 35, height: 45}, 'o-rback3-i-lit': {x: 525, y: 461, width: 35, height: 45}, 'o-rback3-i-out': {x: 525, y: 326, width: 35, height: 45}, 'o-rback3-i-out-lit': {x: 525, y: 371, width: 35, height: 45}, 'o-rback3-s': {x: 578, y: 48, width: 34, height: 45}, 'o-rback3-s-lit-b': {x: 578, y: 138, width: 34, height: 45}, 'o-rback3-s-lit-g': {x: 578, y: 228, width: 34, height: 45}, 'o-rback3-s-lit-r': {x: 578, y: 183, width: 34, height: 45}, 'o-rback3-s-lit-y': {x: 578, y: 93, width: 34, height: 45}, 'o-rback4-i': {x: 560, y: 416, width: 35, height: 45}, 'o-rback4-i-in': {x: 560, y: 506, width: 35, height: 45}, 'o-rback4-i-lit': {x: 560, y: 461, width: 35, height: 45}, 'o-rback4-i-out': {x: 560, y: 326, width: 35, height: 45}, 'o-rback4-i-out-lit': {x: 560, y: 371, width: 35, height: 45}, 'o-rback4-s': {x: 612, y: 48, width: 34, height: 45}, 'o-rback4-s-lit-b': {x: 612, y: 138, width: 34, height: 45}, 'o-rback4-s-lit-g': {x: 612, y: 228, width: 34, height: 45}, 'o-rback4-s-lit-r': {x: 612, y: 183, width: 34, height: 45}, 'o-rback4-s-lit-y': {x: 612, y: 93, width: 34, height: 45}, 'o-right-i': {x: 245, y: 416, width: 35, height: 45}, 'o-right-i-in': {x: 245, y: 506, width: 35, height: 45}, 'o-right-i-lit': {x: 245, y: 461, width: 35, height: 45}, 'o-right-i-out': {x: 245, y: 326, width: 35, height: 45}, 'o-right-i-out-lit': {x: 245, y: 371, width: 35, height: 45}, 'o-right-s': {x: 306, y: 48, width: 34, height: 45}, 'o-right-s-lit-b': {x: 306, y: 138, width: 34, height: 45}, 'o-right-s-lit-g': {x: 306, y: 228, width: 34, height: 45}, 'o-right-s-lit-r': {x: 306, y: 183, width: 34, height: 45}, 'o-right-s-lit-y': {x: 306, y: 93, width: 34, height: 45}, 'o-up0-i': {x: 140, y: 416, width: 35, height: 45}, 'o-up0-i-in': {x: 140, y: 506, width: 35, height: 45}, 'o-up0-i-lit': {x: 140, y: 461, width: 35, height: 45}, 'o-up0-i-out': {x: 140, y: 326, width: 35, height: 45}, 'o-up0-i-out-lit': {x: 140, y: 371, width: 35, height: 45}, 'o-up0-s': {x: 204, y: 48, width: 34, height: 45}, 'o-up0-s-lit-b': {x: 204, y: 138, width: 34, height: 45}, 'o-up0-s-lit-g': {x: 204, y: 228, width: 34, height: 45}, 'o-up0-s-lit-r': {x: 204, y: 183, width: 34, height: 45}, 'o-up0-s-lit-y': {x: 204, y: 93, width: 34, height: 45}, 'o-up1-i': {x: 175, y: 416, width: 35, height: 45}, 'o-up1-i-in': {x: 175, y: 506, width: 35, height: 45}, 'o-up1-i-lit': {x: 175, y: 461, width: 35, height: 45}, 'o-up1-i-out': {x: 175, y: 326, width: 35, height: 45}, 'o-up1-i-out-lit': {x: 175, y: 371, width: 35, height: 45}, 'o-up1-s': {x: 238, y: 48, width: 34, height: 45}, 'o-up1-s-lit-b': {x: 238, y: 138, width: 34, height: 45}, 'o-up1-s-lit-g': {x: 238, y: 228, width: 34, height: 45}, 'o-up1-s-lit-r': {x: 238, y: 183, width: 34, height: 45}, 'o-up1-s-lit-y': {x: 238, y: 93, width: 34, height: 45}, 'o-up_-i': {x: 210, y: 416, width: 35, height: 45}, 'o-up_-i-in': {x: 210, y: 506, width: 35, height: 45}, 'o-up_-i-lit': {x: 210, y: 461, width: 35, height: 45}, 'o-up_-i-out': {x: 210, y: 326, width: 35, height: 45}, 'o-up_-i-out-lit': {x: 210, y: 371, width: 35, height: 45}, 'o-up_-s': {x: 272, y: 48, width: 34, height: 45}, 'o-up_-s-lit-b': {x: 272, y: 138, width: 34, height: 45}, 'o-up_-s-lit-g': {x: 272, y: 228, width: 34, height: 45}, 'o-up_-s-lit-r': {x: 272, y: 183, width: 34, height: 45}, 'o-up_-s-lit-y': {x: 272, y: 93, width: 34, height: 45}, 'o-x-s': {x: 68, y: 48, width: 34, height: 45}, 'o-x-s-lit-b': {x: 68, y: 138, width: 34, height: 45}, 'o-x-s-lit-g': {x: 68, y: 228, width: 34, height: 45}, 'o-x-s-lit-r': {x: 68, y: 183, width: 34, height: 45}, 'o-x-s-lit-y': {x: 68, y: 93, width: 34, height: 45}, 'o10': {x: 16, y: 585, width: 26, height: 25}, 'o11': {x: 42, y: 585, width: 26, height: 25}, 'o12': {x: 68, y: 585, width: 26, height: 25}, 'o13': {x: 94, y: 585, width: 26, height: 25}, 'o14': {x: 120, y: 585, width: 26, height: 25}, 'o15': {x: 146, y: 585, width: 26, height: 25}, 'o16': {x: 172, y: 585, width: 26, height: 25}, 'o17': {x: 198, y: 585, width: 26, height: 25}, 'o20': {x: 577, y: 610, width: 26, height: 25}, 'o21': {x: 603, y: 610, width: 26, height: 25}, 'o22': {x: 629, y: 610, width: 26, height: 25}, 'o23': {x: 655, y: 610, width: 26, height: 25}, 'o24': {x: 681, y: 610, width: 26, height: 25}, 'o25': {x: 707, y: 610, width: 26, height: 25}, 'o26': {x: 733, y: 610, width: 26, height: 25}, 'o27': {x: 759, y: 610, width: 26, height: 25}, 'play-flat': {x: 424, y: 276, width: 45, height: 46}, 'play-in': {x: 469, y: 276, width: 45, height: 46}, 'play-out': {x: 334, y: 276, width: 45, height: 46}, 'play-out-lit': {x: 379, y: 276, width: 45, height: 46}, 'slot-left': {x: 350, y: 610, width: 13, height: 55}, 'slot-right': {x: 0, y: 554, width: 13, height: 55}, 'tape-shadow-l': {x: 350, y: 554, width: 47, height: 41}, 'tape-shadow-r': {x: 511, y: 0, width: 47, height: 41}, 'tape0': {x: 721, y: 0, width: 40, height: 46}, 'tape0a': {x: 561, y: 0, width: 40, height: 46}, 'tape0b': {x: 601, y: 0, width: 40, height: 46}, 'tape0c': {x: 641, y: 0, width: 40, height: 46}, 'tape0d': {x: 681, y: 0, width: 40, height: 46}, 'tape1': {x: 291, y: 276, width: 40, height: 46}, 'tape1a': {x: 131, y: 276, width: 40, height: 46}, 'tape1b': {x: 171, y: 276, width: 40, height: 46}, 'tape1c': {x: 211, y: 276, width: 40, height: 46}, 'tape1d': {x: 251, y: 276, width: 40, height: 46}, 'tape_': {x: 243, y: 554, width: 40, height: 45}, 'target-blank': {x: 0, y: 276, width: 128, height: 47}, 'track': {x: 400, y: 554, width: 369, height: 53}, 'track-l2': {x: 0, y: 0, width: 90, height: 27}, 'track-l3': {x: 109, y: 554, width: 131, height: 27}, 'track-l4': {x: 366, y: 610, width: 173, height: 27}, 'track-short': {x: 0, y: 30, width: 94, height: 8}, 'track-u2': {x: 16, y: 554, width: 90, height: 28}, 'track-u3': {x: 517, y: 276, width: 131, height: 28}, 'track-u4': {x: 577, y: 638, width: 173, height: 28}, 'track-vert': {x: 286, y: 616, width: 7, height: 49} };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Saves and restores persistent game state. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.GameState'); /** * The localStorage key for the current program. * @type {string} * @const * @private */ turing.CUR_PROGRAM_KEY_ = 'doodle-turing-p'; /** * Minimum valid value for curProgram_. * @type {number} * @const * @private */ turing.MIN_VALID_PROGRAM_ = 1; /** * Maximum valid value for curProgram_. * @type {number} * @const * @private */ turing.MAX_VALID_PROGRAM_ = 12; /** * The current game state. * @constructor */ turing.GameState = function() { /** * Index of the current program. * @type {number} * @private */ this.curProgram_ = turing.MIN_VALID_PROGRAM_; }; /** * @return {number} Index of current program. */ turing.GameState.prototype.getCurProgram = function() { return this.curProgram_; }; /** * Sets index of current program. * @param {number} curProgram The index of the current program. */ turing.GameState.prototype.setCurProgram = function(curProgram) { this.curProgram_ = curProgram; this.save(); }; /** * Saves state using localStorage. */ turing.GameState.prototype.save = function() { if (window.localStorage && window.localStorage.setItem) { window.localStorage.setItem(turing.CUR_PROGRAM_KEY_, this.curProgram_); } }; /** * Restores state using localStorage. */ turing.GameState.prototype.restore = function() { if (window.localStorage && window.localStorage[turing.CUR_PROGRAM_KEY_]) { this.curProgram_ = parseInt( window.localStorage[turing.CUR_PROGRAM_KEY_], 10) || 0; // NaN -> 0. if (this.curProgram_ < turing.MIN_VALID_PROGRAM_ || this.curProgram_ > turing.MAX_VALID_PROGRAM_) { // If curProgram_ is corrupted, start from the first program. this.curProgram_ = turing.MIN_VALID_PROGRAM_; } } };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A small collection of helpers. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.util'); /** * Browser vendor name prefixes, used for looking up vendor-specific properties. * Other known vendor prefixes include 'Khtml' and 'Icab', but I'm excluding * these because I don't have them available to test. * @type {Array.<string>} * @const */ turing.VENDOR_PREFIXES = ['Moz', 'Webkit', 'O', 'ms']; /** * Removes an element from its dom parent. * @param {Element} elem The element to remove. */ turing.util.removeNode = function(elem) { if (elem && elem.parentNode) { elem.parentNode.removeChild(elem); } }; /** * Chooses the value after value in arr, or null if not in arr. * @param {Array} arr An array to search in. * @param {*} value The value to search for. * @return {*} The value after the searched one, or null if none. */ turing.util.getNextValue = function(arr, value) { for (var i = 0, arrValue; arrValue = arr[i]; i++) { if (arrValue == value) { break; } } var nextValue = i == arr.length - 1 ? arr[0] : arr[i + 1]; return i == arr.length ? null : nextValue; }; /** * Gets the vendor-specific name of a CSS property. * Adapted from https://gist.github.com/556448 * @param {string} property The standard name of a CSS property. * @return {string|undefined} The name of this property as implemented in the * current browser, or undefined if not implemented. */ turing.util.getVendorCssPropertyName = function(property) { var body = document.body || document.documentElement; var style = body.style; if (typeof style == 'undefined') { // No CSS support. Something is badly wrong. return undefined; } if (typeof style[property] == 'string') { // The standard name is supported. return property; } // Test for vendor specific names. var capitalizedProperty = property.charAt(0).toUpperCase() + property.substr(1); for (var i = 0, prefix; prefix = turing.VENDOR_PREFIXES[i++]; ) { if (typeof style[prefix + capitalizedProperty] == 'string') { return prefix + capitalizedProperty; } } }; /** * Calls either addEventListener or attachEvent depending on what's * available. * @param {(Document|Element|Window)} element The object to listen on. * @param {string} eventName The event to listen to, such as 'click'. * @param {Function} listener The listener function to trigger. */ turing.util.listen = function(element, eventName, listener) { if (element.addEventListener) { element.addEventListener(eventName, listener, false); } else { element.attachEvent('on' + eventName, listener); } }; /** * Stops listening to the specified event on the given target. * @param {(Document|Element|Window)} element The object that we were listening * on. * @param {string} eventName The event we were listening to, such as 'click'. * @param {Function} listener The listener function to remove. */ turing.util.unlisten = function(element, eventName, listener) { if (!element || !listener) { return; } if (element.removeEventListener) { element.removeEventListener(eventName, listener, false); } else if (element.detachEvent) { element.detachEvent('on' + eventName, listener); } }; /** * Sets the opacity of a node (x-browser). * @param {Element} el Elements whose opacity has to be set. * @param {number|string} alpha Opacity between 0 and 1 or an empty string * {@code ''} to clear the opacity. */ turing.util.setOpacity = function(el, alpha) { var style = el.style; if ('opacity' in style) { style.opacity = alpha; } else if ('MozOpacity' in style) { style.MozOpacity = alpha; } else if ('filter' in style) { if (alpha === '') { style.filter = ''; } else { style.filter = 'alpha(opacity=' + alpha * 100 + ')'; } } };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview An interactive doodle for Alan Turing's 100th birthday. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing'); goog.require('turing.Controls'); goog.require('turing.GameState'); goog.require('turing.Logo'); goog.require('turing.Program'); goog.require('turing.Simulator'); goog.require('turing.Tape'); goog.require('turing.Target'); goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); /** * The container where our dom modifications will be contained. * @type {string} * @const */ turing.LOGO_CONTAINER_ID = 'logo'; /** * The maximum number of steps a game program can run. This should be just high * enough so that all halting programs can run fully, and all cyclic programs do * something that checks wrong before we kill them; but low enough so that users * don't get bored if they make a trivial infinite loop. * @type {number} * @const */ turing.GAME_PROGRAM_STEP_LIMIT = 40; /** * How many failed attempts at current puzzle before we slow down execution. * @type {number} * @const */ turing.FAILURES_BEFORE_SLOWING = 2; /** * Assembles a program from strings. * @param {...string} var_args One string for each program track. * @return {Object.<string, Array.<Array.<string>>>} An object with correct and * incorrect array of op arrays for each track. * @private */ turing.assemble_ = function(var_args) { var ops = {}; for (var pass = 0; pass <= 1; pass++) { // Make two passes through each program to save incorrect and correct // copies. We need correct copies to animate stepping through solved puzzles // when the game is over. var tracks = []; for (var i = 0; i < arguments.length; i++) { // Split on whitespace and copy the resulting array (/ +/ matches one or // more spaces.) var trackOps = arguments[i].split(/ +/).slice(0); for (var j = 0; j < trackOps.length; j++) { if (trackOps[j] == '.') { // No-ops are represented internally with the empty string. trackOps[j] = ''; } else if (/\(.*\)/.test(trackOps[j])) { // /\(.*\)/ matches a parenthesized expression inside the op // description. These are corrections for ops initially set to a wrong // value for the game. if (pass == 0) { // Keep only the correction. (The re below matches the whole op // string, but captures only the part in parentheses.) trackOps[j] = trackOps[j].replace(/.*\((.*)\).*/, '$1'); } else { // Eliminate the correction. trackOps[j] = '*' + trackOps[j].replace(/\(.*\)/, ''); } } else if (pass == 0 && trackOps[j] && trackOps[j][0] == '*') { // Some buttons are clickable but do not have explicit corrections // since they are not needed to solve the program. These are just // marked with a *. Remove it if present so they are not clickable // when playing through the solved program on game over. trackOps[j] = trackOps[j].substr(1); } } tracks.push(trackOps); } if (pass == 0) { ops.correct = tracks; } else { ops.incorrect = tracks; } } return ops; }; /** * One of the doodle's programs. * @typedef {{tape: string, goal: string, ops: Object.<string, Array>}} */ turing.ProgramDef; /** * The set of programs which the user must complete in order to relight the * Google logo, along with an initial demo/demos to show off the machine. * @type {Array.<turing.ProgramDef>} * @const */ turing.PROGRAMS = [ // Demo program shown when the doodle loads. { // This program counts forever in binary starting at 1. tape: '', goal: '', ops: turing.assemble_('D0 D_ 0 L B4', '. 1 R U_ B2') }, // First quest: The following six programs are four basic tutorial programs // and two interesting but not especially challenging programs. We hope most // people can get through these with no trouble. { tape: '00010', goal: '01011', // A really gentle intro to the basic operations: just moves and prints. // - Tried L L *0, but most users clicked through without understanding. // - Tried L L 1(0) R R R R 0(1) with the tape 11010. Needing to click two // things reduced random click throughs, but some users were stuck here // when buttons cycled L/R/0/1 (so now they cycle 0/1). // - Considered the above program with the tape _101_ to make printing more // obvious, but decided the first program needs to start with a five bit // string on the tape for clear correspondence with the number plate. // - Revised to this program because we want the leftmost bit to be correct // so at first the user sees one bit check correct and then one wrong. ops: turing.assemble_('L 0(1) R R R 0(1)'), tutorial: true, logoLetterIndex: 0, highlight: 'b' }, { tape: '0_011', goal: '00011', // Introduces conditional branching between tracks, the down-if operation // and the notation we use to mean a blank square. // - The extra L is supposed to give users time to notice the program is // running. // - We tried 0 *D0 followed by some Ls and Rs on each track. Users clicked // through but were generally confused about our notation, so we didn't // learn much. Also we had aesthetic complaints about branching on // something just written. ops: turing.assemble_('L D0(D_) 1', '. 0'), tutorial: true, logoLetterIndex: 1, highlight: 'r' }, { tape: '01011', goal: '00011', // Introduces backwards branches. The goal is to line up with the correct // conditional. The extra Rs are supposed to show there is an incorrect // alternative path; hopefully this is not confusing. // - We tried a more elaborate program with a loop where one had to pick the // correct exit. This was too complex. Users had trouble noticing the // backwards arcing tracks, which this program really emphasizes visually // since it lines up with the descending track from the D1 ops. ops: turing.assemble_('D1 D1 D1 L B2(B4)', '0 R R R'), tutorial: true, logoLetterIndex: 2, highlight: 'y' }, { tape: '11011', goal: '01011', // Introduces loops. Finds the first bit and changes it. ops: turing.assemble_('L D1(D_) B2', '. R 0'), tutorial: true, logoLetterIndex: 3, highlight: 'b' }, { tape: '0_001', goal: '01001', // Replaces a single blank with 1s. // This would be more challenging if the D1 exit were changeable. ops: turing.assemble_('L L D0(D_) R D1 B3', '. . 1 U1'), logoLetterIndex: 4, highlight: 'g' }, { tape: '01111', goal: '10000', // Inverts the string on the tape. // This is an actual interesting program with a clear task. Two different // solutions work to make the program do inverting; on track 2, 0 -> 1, // U0 -> U1; or on track 1, D0 -> D1, 0 -> 1. ops: turing.assemble_('L L D0(D1) 0(1) R D_ B4', '. . *0 . *U0'), logoLetterIndex: 5, highlight: 'r' }, // Second quest: These more interesting programs are here for users who // really like this sort of thing and want more challenge/interest. { tape: '11010', goal: '01011', // Uses loops to find the first and last bits and change them. ops: turing.assemble_('L D_ B2 . R(L) 1', '. R 0 R U0(U_) B2'), logoLetterIndex: 0, highlight: 'b' }, { tape: '01_01', goal: '00011', // Adds two base one numbers, sort of, not really. ops: turing.assemble_('L D_(D1) B2 . L 1 L 0', '. . 0 R U_(U1) B2 . .'), logoLetterIndex: 1, highlight: 'r' }, { tape: '00111', goal: '00011', // A maze of conditionals. This is maybe sort of insane. ops: turing.assemble_('D_(D1) 1 L D_(D1) 1 L D_(D0) 1', '1 R U_(U1) 0 R U_(U1) 0 *U_'), logoLetterIndex: 2, highlight: 'y' }, { tape: '01011', goal: '01011', // A goofy easy one to break up the tension. So easy it actually does // nothing. This is an homage to the Konami code. ops: turing.assemble_('. . D_ D_ L R L R', 'U_ U_ . . . . 1 0'), tutorial: true, logoLetterIndex: 3, highlight: 'b' }, { tape: '0_00_', goal: '01001', // Replaces zeroes followed by blanks with 1s. // This is meant to be sort of challenging. The main challenge is to avoid // infinite loops and reason about what makes the program terminate // properly. ops: turing.assemble_('L L D_(D0) 1 R D1(D_) B4', '. R U0(U_) B2'), logoLetterIndex: 4, highlight: 'g' }, { tape: '00001', goal: '10000', // Shifts the one to left. ops: turing.assemble_('D0(D1) R . D0(D_) B4', '0 L 1 L U_(U0)'), stepLimit: 80, logoLetterIndex: 5, highlight: 'r' } ]; /** * A bonus program displayed only in a special mode which the user can trigger * after winning the game. This program prints the rabbit sequence, which is a * bitstring with many beautiful relationships to Fibonacci numbers and the * golden ratio. More immediately, it implements the substitution system with * rules 1 -> 10, 0 -> 1. * @type {Array.<Array.<string>>} * @const */ turing.BONUS_PROGRAM = turing.assemble_( '1 . D1 . . . . _ R D_ B2', 'R U _ R D_ B2 . 1 B8 1 D_ L B2', 'U . B2 . 1 R 0 U_ L B2 0 B9').correct; /** * Current game state. * @type {turing.GameState} * @private */ turing.state_ = new turing.GameState(); /** * True iff the game has ended. * @type {boolean} * @private */ turing.gameOver_ = false; /** * How many times has the user failed to solve the current puzzle? * @type {number} * @private */ turing.numFailures_ = 0; /** * The time when the current program was first set up. * @type {number} * @private */ turing.startProgramTime_ = 0; /** * The tape. * @type {turing.Tape} * @private */ turing.tape_; /** * The letters of the Google logo. * @type {turing.Logo} * @private */ turing.logo_ = new turing.Logo(); /** * The program display. * @type {turing.Program} * @private */ turing.program_; /** * An overlay which covers the doodle initially. * @type {turing.Overlay} * @private */ turing.overlay_ = new turing.Overlay(); /** * Helper to simulate programs. * @type {turing.Simulator} * @private */ turing.simulator_ = new turing.Simulator(); /** * Controls to start and stop program execution. * @type {turing.Controls} * @private */ turing.controls_ = new turing.Controls(); /** * A board to display the desired target for the current game program. * @type {turing.Target} * @private */ turing.target_ = new turing.Target(); /** * The main container for the doodle. * @type {Element} * @private */ turing.logoContainer_ = null; /** * @return {boolean} True iff current program is a tutorial. * @private */ turing.inTutorial_ = function() { return turing.PROGRAMS[turing.state_.getCurProgram()].tutorial; }; /** * @param {Element} img An img element. * @return {boolean} True iff an image is already loaded. * @private */ turing.isImageReady_ = function(img) { return img['complete'] || img['readyState'] == 'complete'; }; /** * Starts up demo mode. * @private */ turing.startDemo_ = function() { turing.logo_.attachTo(turing.logoContainer_); turing.tape_.attachTo(turing.logoContainer_); turing.program_.attachTo(turing.logoContainer_); turing.overlay_.attachTo(turing.logoContainer_, turing.startGame_); turing.controls_.attachTo(turing.logoContainer_); turing.target_.attachTo(turing.logoContainer_); // Remove the base overlay image which we show while our sprite preloads. turing.logoContainer_.style.background = ''; turing.startSleepTimer_(); turing.program_.setInteractive(false); turing.program_.change(turing.PROGRAMS[0].ops.correct, true /* Hidden. */); turing.simulator_.run(turing.program_, turing.tape_, turing.SpeedSetting.FAST); }; /** * Changes into game mode. * @private */ turing.startGame_ = function() { // Begin loading the deferred sprite sheet. var deferredSprite = turing.sprites.preload( turing.sprites.DEFERRED_SPRITE_PATH); turing.simulator_.stop(); turing.simulator_.setStepLimit(turing.GAME_PROGRAM_STEP_LIMIT); if (turing.PROGRAMS[turing.state_.getCurProgram()].logoLetterIndex == 0) { // Only dim the logo if the user hasn't solved any programs yet, i.e., they // are on the 'G' program; otherwise we'll pick up where they left off. turing.logo_.dim(500); } if (turing.isImageReady_(deferredSprite)) { // If the deferred sprite was cached or loaded very fast, go right to the // game. turing.destroySleepTimer_(); turing.anim.delay(function() { turing.setupProgram_(turing.state_.getCurProgram()); }, 500); } else { // Otherwise, if we're waiting for the deferred sprite, treat the tape as a // progress bar and sit scrolling it until the sprite loads. var loaded = false; turing.anim.delay(function() { if (!loaded) { turing.tape_.scanRight(100, 100); turing.anim.delay(/** @type {function()} */(arguments.callee), 300); } }, 300); deferredSprite.onload = function() { loaded = true; turing.destroySleepTimer_(); turing.setupProgram_(turing.state_.getCurProgram()); }; } }; /** * Sets up the game for a given program. * Things change in the order: Target, tape, program (top to bottom). * @param {number} index The program to enter. * @private */ turing.setupProgram_ = function(index) { var program = turing.PROGRAMS[index]; turing.startProgramTime_ = new Date().getTime(); if (program.stepLimit) { turing.simulator_.setStepLimit(program.stepLimit); } // Make the program vanish and the target scroll away. turing.program_.change([[], []]); turing.target_.setValue('', 800); turing.target_.setEqual('dim'); turing.anim.delay(turing.callIfNotInBonusMode_(function() { turing.tape_.setString(program.tape); }), 800); turing.anim.delay(turing.callIfNotInBonusMode_(function() { turing.target_.setValue(program.goal, 800); }), 2200); turing.anim.delay(turing.callIfNotInBonusMode_(function() { if (!turing.gameOver_) { turing.program_.change(program.ops.incorrect); turing.makeInteractive_(0, 500); } else { turing.program_.change(program.ops.correct); // The bunny takes you to bonus mode! turing.target_.showBonusBunny(turing.enterBonusMode_, program.highlight); turing.setOpHighlightColor(program.highlight); turing.simulator_.run(turing.program_, turing.tape_, turing.SpeedSetting.FAST, turing.callIfNotInBonusMode_(function() { turing.winLevel_(index); })); } }), 3200); }; /** * Changes program and makes the play button pressable after the tape is set up. * @param {number} popOutPlayDelay ms to delay before popping button out. * @param {number} lightOpsDelay ms to delay before lighting clickable buttons. * @private */ turing.makeInteractive_ = function(popOutPlayDelay, lightOpsDelay) { turing.target_.setEqual('dim'); turing.anim.delay(function() { turing.controls_.popOutPlayButton(function() { turing.program_.setInteractive(false); turing.controls_.pushInPlayButton(); // Pause between lighting the play button and lighting the first // operation to make it clear these are two separate things happening. turing.anim.delay(function() { // Speed picks up a little after the initial programs, but slows back // down if the user has trouble. var speed = turing.inTutorial_() ? turing.SpeedSetting.TUTORIAL : turing.SpeedSetting.NORMAL; if (turing.numFailures_ >= turing.FAILURES_BEFORE_SLOWING) { // Having a hard time. speed = turing.inTutorial_() ? turing.SpeedSetting.SLOW : turing.SpeedSetting.TUTORIAL; } // Note: I tried dropping back down to SLOW if there are twice as many // failures, but this is just too slow for looping programs. turing.simulator_.run(turing.program_, turing.tape_, speed, turing.finishProgramRun_); }, 600); }); // Light up clickable ops a little after the play button pops out so that // people will first notice the play button, then things to click. turing.anim.delay(function() { turing.program_.setInteractive(true); }, lightOpsDelay); }, popOutPlayDelay); }; /** * Ends the game after the user has won. * This method is called twice: * - once to signal that the user has finished the game and start an * animation of the play-through. * - then, it is called again but instead navigates to serp. * @private */ turing.endGame_ = function() { turing.tape_.setString(''); turing.program_.change([[], []]); turing.program_.reset(); turing.target_.setValue('', 800); if (!turing.gameOver_) { if (turing.state_.getCurProgram() == turing.PROGRAMS.length - 1) { // Reset current program so the next playthrough will start over. turing.state_.setCurProgram(1); } else { // On next playthrough, begin at a new set of programs. turing.state_.setCurProgram(turing.state_.getCurProgram() + 1); } turing.gameOver_ = true; turing.anim.delay( goog.bind(turing.logo_.deluminate, turing.logo_, turing.replaySolutionsInSequence_), 1000); } else { window.location.href = '/search?q=Alan+Turing'; } turing.target_.setEqual('dim'); }; /** * Plays through solved programs in sequence. * @private */ turing.replaySolutionsInSequence_ = function() { // Because gameOver is now set, setupProgram_ will just step through programs // until the last. // We have already set up the new value of curProgram for the next game. Count // back six programs, wrapping, to figure out which program began this game, // so we can replay from the correct place. var firstProgramInNextGame = turing.state_.getCurProgram(); var firstProgramInThisGame = firstProgramInNextGame == 1 ? turing.PROGRAMS.length - 6 : firstProgramInNextGame - 6; turing.setupProgram_(firstProgramInThisGame); }; /** * Sets up a more complicated, interesting program after the game is done. * @private */ turing.enterBonusMode_ = function() { turing.simulator_.stop(); turing.logo_.destroy(); turing.controls_.destroy(); turing.target_.destroy(); turing.program_.destroy(); turing.switchProgramsToBonusMode(); turing.setOpHighlightColor('y'); turing.startSleepTimer_(); turing.tape_.slideUp(); turing.anim.delay(function() { // There may be another setString queued, so wait a while and then clear // the tape to be sure it starts out blank. turing.tape_.setString(''); turing.anim.delay(function() { turing.program_ = new turing.Program(); turing.program_.create(); turing.program_.attachTo(turing.logoContainer_); turing.program_.change(turing.BONUS_PROGRAM); turing.simulator_.setStepLimit(0); turing.simulator_.run(turing.program_, turing.tape_, turing.SpeedSetting.FAST); }, 2000); }, 2000); }; /** * Wraps a function with a test to check for bonus mode prior to calling. * @param {function()} func The function to call. * @return {function()} A function which first tests for bonus mode. * @private */ turing.callIfNotInBonusMode_ = function(func) { return function() { if (!turing.isInBonusMode()) { func(); } } }; /** * Called when a program is finished running. * @private */ turing.finishProgramRun_ = function() { // Let the last operation light remain off for a while to make it clear the // program is done. turing.anim.delay(function() { // First dim, but do not pop out the play button. turing.controls_.dimPlayButton(); // Give the user just long enough to notice the play button before starting // to check the tape. turing.anim.delay(turing.checkTape_, 1000); }, 700); }; /** * Checks to see whether the tape is correct * @private */ turing.checkTape_ = function() { // -1 seeks one position left of the first square to attract attention to // checking before it starts. turing.checkNextSquare_(-1, turing.winLevel_, turing.failLevel_); }; /** * Called when the user wins a level (the tape checks correct). * @param {number=} opt_index Iff present, use this as the index of the program * just completed. * @private */ turing.winLevel_ = function(opt_index) { turing.numFailures_ = 0; var index = opt_index || turing.state_.getCurProgram(); var letterIndex = turing.PROGRAMS[index].logoLetterIndex; // Change the current letter to be lit up. turing.logo_.lightLetterAtPosition(letterIndex, 500); if (!turing.isInBonusMode() && letterIndex == 5 /* 'e'. */) { // End the game when the 'e' program is solved. turing.anim.delay(turing.endGame_, 500); } else if (opt_index) { // Run new program but don't update state; used for end-game animation. turing.anim.delay(turing.callIfNotInBonusMode_(function() { turing.setupProgram_(/** @type {number} */(opt_index) + 1); }), 500); } else { // Update state. turing.anim.delay(turing.callIfNotInBonusMode_(function() { turing.state_.setCurProgram(index + 1); turing.setupProgram_(turing.state_.getCurProgram()); }), 500); } }; /** * Called when the user fails the level (tape doesn't check.) * @private */ turing.failLevel_ = function() { // Reset the tape and try again. turing.numFailures_++; var program = turing.PROGRAMS[turing.state_.getCurProgram()]; turing.anim.delay(function() { turing.tape_.resetString(program.tape); turing.anim.delay(function() { turing.makeInteractive_(0, 100); turing.program_.reset(); }, 400); }, 300); }; /** * Check the square in the tape pointed to by the index arg. * If it's past the last symbol on the tape and in the target, then * trigger success. * If it doesn't match the target's symbol at index, then trigger failure. * Otherwise wait a bit and check the next square. * @param {number} index The index to check. * @param {function()} successCallback What to do if all squares match * the target. * @param {function()} failureCallback What to do if there is a mismatch. * @private */ turing.checkNextSquare_ = function(index, successCallback, failureCallback) { var symbol = turing.tape_.scanToAndGetSymbol(index); var program = turing.PROGRAMS[turing.state_.getCurProgram()]; if (index == -1) { // First scan one square to the left of the solution to get people to // look up to the tape. turing.anim.delay( goog.partial(turing.checkNextSquare_, index + 1, successCallback, failureCallback), 600); return; } if (!symbol && !program.goal[index]) { turing.target_.highlightAt(program.goal, index, 1600); turing.target_.setEqual('eq', 1600); // Success. We've gone off the end of both strings. turing.anim.delay(successCallback, 2000); } else if (symbol != program.goal[index]) { turing.target_.highlightAt(program.goal, index, 1600); turing.target_.setEqual('neq', 1600); // Fail! turing.anim.delay(failureCallback, 2000); } else { // Speed up checking after we've passed the intro programs. var duration = turing.inTutorial_() ? 1000 : 500; turing.target_.highlightAt(program.goal, index, duration); turing.target_.setEqual('eq', duration - 200); turing.anim.delay( goog.partial(turing.checkNextSquare_, index + 1, successCallback, failureCallback), duration); } }; /** * Id for a timer which puts the doodle to sleep due to inactivity. * @type {?number} * @private */ turing.sleepTimerId_ = null; /** * True iff we saw the mouse move since the last sleep timer callback. * @type {boolean} * @private */ turing.sawMouseMove_ = false; /** * Period in ms of a timer which checks if it should put the doodle to sleep. * Note this means the doodle must be inactive for [t, 2*t] before going to * sleep. * @type {number} * @const */ turing.SLEEP_TIMEOUT = 20000; /** * Sets up a timer to put the doodle to sleep after a period of inactivity. * @private */ turing.startSleepTimer_ = function() { // Inactivity is defined as no mouse movement for a period of the sleep timer. turing.sawMouseMove_ = false; turing.util.listen(document, 'mousemove', turing.mouseMoveListener_); turing.util.listen(document, 'touchstart', turing.touchStartListener_); // Put the doodle to sleep when simulator is running with no user activity. turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_, turing.SLEEP_TIMEOUT); }; /** * Event listener for mouse movements on the document element. Used to detect * long periods of inactivity and put the doodle to sleep. * @private */ turing.mouseMoveListener_ = function() { turing.sawMouseMove_ = true; if (turing.anim.isStopped()) { // Wake the doodle up immediately so the user doesn't see it paused. turing.anim.start(); turing.simulator_.resumeIfPaused(); turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_, turing.SLEEP_TIMEOUT); } }; /** * Event listener for touchstart events. * @private */ turing.touchStartListener_ = function() { turing.program_.setTouchDevice(); turing.mouseMoveListener_(); }; /** * Called periodically to put the doodle to sleep if it is inactive. * @private */ turing.sleepIfInactive_ = function() { if (turing.simulator_.isRunning() && !turing.simulator_.hasStepLimit() && !turing.sawMouseMove_) { // Only sleep if the simulator is running forever; the game settles down to // an idle steady state when playing. turing.simulator_.pause(); turing.anim.stop(); } else { turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_, turing.SLEEP_TIMEOUT); } // This will be reset in onmousemove if the user is mousing. turing.sawMouseMove_ = false; }; /** * Tears down the sleep timeout timer. * @private */ turing.destroySleepTimer_ = function() { turing.util.unlisten(document, 'mousemove', turing.mouseMoveListener_); turing.util.unlisten(document, 'touchstart', turing.touchStartListener_); if (turing.sleepTimerId_ != null) { window.clearTimeout(turing.sleepTimerId_); turing.sleepTimerId_ = null; } }; /** * Preloads sprite, creates dom elements and binds event listeners. */ turing.init = function() { turing.logoContainer_ = document.getElementById(turing.LOGO_CONTAINER_ID); if (!turing.logoContainer_) { // Do not show if the logo container is missing. return; } var mainSprite = turing.sprites.preload(turing.sprites.PATH); turing.state_.restore(); turing.anim.reset(); turing.anim.start(); // In case we were previously in bonus mode. turing.switchProgramsToNormalMode(); turing.setOpHighlightColor('y'); turing.program_ = new turing.Program(); turing.gameOver_ = false; turing.numFailures_ = 0; turing.overlay_.create(turing.logoContainer_); // If the user has not solved the 'G' program, light the entire logo // initially, else light as many letters as they have solved. var curProgram = turing.state_.getCurProgram(); var letterIndex = turing.PROGRAMS[curProgram].logoLetterIndex; turing.logo_.create(letterIndex == 0 ? 6 : letterIndex); turing.tape_ = new turing.Tape(); turing.tape_.create(); turing.program_.create(); turing.controls_.create(); turing.target_.create(); // Start the demo when we have the image for the main sprite. // Set up the handlers after we've initialized everything above as // the handler does use some of those objects. if (turing.isImageReady_(mainSprite)) { turing.startDemo_(); } else { mainSprite.onload = turing.startDemo_; } }; /** * Cleans up dom elements and listeners. */ turing.destroy = function() { turing.state_.save(); turing.destroySleepTimer_(); turing.anim.reset(); turing.simulator_.stop(); turing.target_.destroy(); turing.overlay_.destroy(); if (turing.program_) { turing.program_.destroy(); turing.program_ = null; } if (turing.tape_) { turing.tape_.destroy(); turing.tape_ = null; } turing.logo_.destroy(); turing.controls_.destroy(); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Offsets for sprites. Auto-generated; do not edit. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.deferredsprites.offsets'); goog.require('turing.sprites.offsets'); /** * Bounding boxes of sprites in combined image. * @type {Object.<string, turing.sprites.offsets.Rect>} */ turing.deferredsprites.offsets.RECTS = { 'light-00011-0': {x: 2454, y: 0, width: 129, height: 47}, 'light-00011-1': {x: 2583, y: 0, width: 129, height: 47}, 'light-00011-10': {x: 3744, y: 0, width: 129, height: 47}, 'light-00011-11': {x: 3873, y: 0, width: 129, height: 47}, 'light-00011-12': {x: 4002, y: 0, width: 129, height: 47}, 'light-00011-2': {x: 2712, y: 0, width: 129, height: 47}, 'light-00011-3': {x: 2841, y: 0, width: 129, height: 47}, 'light-00011-4': {x: 2970, y: 0, width: 129, height: 47}, 'light-00011-5': {x: 3099, y: 0, width: 129, height: 47}, 'light-00011-6': {x: 3228, y: 0, width: 129, height: 47}, 'light-00011-7': {x: 3357, y: 0, width: 129, height: 47}, 'light-00011-8': {x: 3486, y: 0, width: 129, height: 47}, 'light-00011-9': {x: 3615, y: 0, width: 129, height: 47}, 'light-01001-0': {x: 2454, y: 47, width: 129, height: 47}, 'light-01001-1': {x: 2583, y: 47, width: 129, height: 47}, 'light-01001-10': {x: 3744, y: 47, width: 129, height: 47}, 'light-01001-11': {x: 3873, y: 47, width: 129, height: 47}, 'light-01001-12': {x: 4002, y: 47, width: 129, height: 47}, 'light-01001-2': {x: 2712, y: 47, width: 129, height: 47}, 'light-01001-3': {x: 2841, y: 47, width: 129, height: 47}, 'light-01001-4': {x: 2970, y: 47, width: 129, height: 47}, 'light-01001-5': {x: 3099, y: 47, width: 129, height: 47}, 'light-01001-6': {x: 3228, y: 47, width: 129, height: 47}, 'light-01001-7': {x: 3357, y: 47, width: 129, height: 47}, 'light-01001-8': {x: 3486, y: 47, width: 129, height: 47}, 'light-01001-9': {x: 3615, y: 47, width: 129, height: 47}, 'light-01011-0': {x: 2454, y: 94, width: 129, height: 47}, 'light-01011-1': {x: 2583, y: 94, width: 129, height: 47}, 'light-01011-10': {x: 3744, y: 94, width: 129, height: 47}, 'light-01011-11': {x: 3873, y: 94, width: 129, height: 47}, 'light-01011-12': {x: 4002, y: 94, width: 129, height: 47}, 'light-01011-2': {x: 2712, y: 94, width: 129, height: 47}, 'light-01011-3': {x: 2841, y: 94, width: 129, height: 47}, 'light-01011-4': {x: 2970, y: 94, width: 129, height: 47}, 'light-01011-5': {x: 3099, y: 94, width: 129, height: 47}, 'light-01011-6': {x: 3228, y: 94, width: 129, height: 47}, 'light-01011-7': {x: 3357, y: 94, width: 129, height: 47}, 'light-01011-8': {x: 3486, y: 94, width: 129, height: 47}, 'light-01011-9': {x: 3615, y: 94, width: 129, height: 47}, 'light-10000-0': {x: 2454, y: 141, width: 129, height: 47}, 'light-10000-1': {x: 2583, y: 141, width: 129, height: 47}, 'light-10000-10': {x: 3744, y: 141, width: 129, height: 47}, 'light-10000-11': {x: 3873, y: 141, width: 129, height: 47}, 'light-10000-12': {x: 4002, y: 141, width: 129, height: 47}, 'light-10000-2': {x: 2712, y: 141, width: 129, height: 47}, 'light-10000-3': {x: 2841, y: 141, width: 129, height: 47}, 'light-10000-4': {x: 2970, y: 141, width: 129, height: 47}, 'light-10000-5': {x: 3099, y: 141, width: 129, height: 47}, 'light-10000-6': {x: 3228, y: 141, width: 129, height: 47}, 'light-10000-7': {x: 3357, y: 141, width: 129, height: 47}, 'light-10000-8': {x: 3486, y: 141, width: 129, height: 47}, 'light-10000-9': {x: 3615, y: 141, width: 129, height: 47}, 'scroll-00011-0': {x: 0, y: 47, width: 129, height: 47}, 'scroll-00011-1': {x: 129, y: 47, width: 129, height: 47}, 'scroll-00011-10': {x: 1290, y: 47, width: 129, height: 47}, 'scroll-00011-11': {x: 1419, y: 47, width: 129, height: 47}, 'scroll-00011-12': {x: 1548, y: 47, width: 129, height: 47}, 'scroll-00011-13': {x: 1677, y: 47, width: 129, height: 47}, 'scroll-00011-14': {x: 1806, y: 47, width: 129, height: 47}, 'scroll-00011-15': {x: 1935, y: 47, width: 129, height: 47}, 'scroll-00011-16': {x: 2064, y: 47, width: 129, height: 47}, 'scroll-00011-17': {x: 2193, y: 47, width: 129, height: 47}, 'scroll-00011-18': {x: 2322, y: 47, width: 129, height: 47}, 'scroll-00011-2': {x: 258, y: 47, width: 129, height: 47}, 'scroll-00011-3': {x: 387, y: 47, width: 129, height: 47}, 'scroll-00011-4': {x: 516, y: 47, width: 129, height: 47}, 'scroll-00011-5': {x: 645, y: 47, width: 129, height: 47}, 'scroll-00011-6': {x: 774, y: 47, width: 129, height: 47}, 'scroll-00011-7': {x: 903, y: 47, width: 129, height: 47}, 'scroll-00011-8': {x: 1032, y: 47, width: 129, height: 47}, 'scroll-00011-9': {x: 1161, y: 47, width: 129, height: 47}, 'scroll-01001-0': {x: 0, y: 94, width: 129, height: 47}, 'scroll-01001-1': {x: 129, y: 94, width: 129, height: 47}, 'scroll-01001-10': {x: 1290, y: 94, width: 129, height: 47}, 'scroll-01001-11': {x: 1419, y: 94, width: 129, height: 47}, 'scroll-01001-12': {x: 1548, y: 94, width: 129, height: 47}, 'scroll-01001-13': {x: 1677, y: 94, width: 129, height: 47}, 'scroll-01001-14': {x: 1806, y: 94, width: 129, height: 47}, 'scroll-01001-15': {x: 1935, y: 94, width: 129, height: 47}, 'scroll-01001-16': {x: 2064, y: 94, width: 129, height: 47}, 'scroll-01001-17': {x: 2193, y: 94, width: 129, height: 47}, 'scroll-01001-18': {x: 2322, y: 94, width: 129, height: 47}, 'scroll-01001-2': {x: 258, y: 94, width: 129, height: 47}, 'scroll-01001-3': {x: 387, y: 94, width: 129, height: 47}, 'scroll-01001-4': {x: 516, y: 94, width: 129, height: 47}, 'scroll-01001-5': {x: 645, y: 94, width: 129, height: 47}, 'scroll-01001-6': {x: 774, y: 94, width: 129, height: 47}, 'scroll-01001-7': {x: 903, y: 94, width: 129, height: 47}, 'scroll-01001-8': {x: 1032, y: 94, width: 129, height: 47}, 'scroll-01001-9': {x: 1161, y: 94, width: 129, height: 47}, 'scroll-01011-0': {x: 0, y: 0, width: 129, height: 47}, 'scroll-01011-1': {x: 129, y: 0, width: 129, height: 47}, 'scroll-01011-10': {x: 1290, y: 0, width: 129, height: 47}, 'scroll-01011-11': {x: 1419, y: 0, width: 129, height: 47}, 'scroll-01011-12': {x: 1548, y: 0, width: 129, height: 47}, 'scroll-01011-13': {x: 1677, y: 0, width: 129, height: 47}, 'scroll-01011-14': {x: 1806, y: 0, width: 129, height: 47}, 'scroll-01011-15': {x: 1935, y: 0, width: 129, height: 47}, 'scroll-01011-16': {x: 2064, y: 0, width: 129, height: 47}, 'scroll-01011-17': {x: 2193, y: 0, width: 129, height: 47}, 'scroll-01011-18': {x: 2322, y: 0, width: 129, height: 47}, 'scroll-01011-2': {x: 258, y: 0, width: 129, height: 47}, 'scroll-01011-3': {x: 387, y: 0, width: 129, height: 47}, 'scroll-01011-4': {x: 516, y: 0, width: 129, height: 47}, 'scroll-01011-5': {x: 645, y: 0, width: 129, height: 47}, 'scroll-01011-6': {x: 774, y: 0, width: 129, height: 47}, 'scroll-01011-7': {x: 903, y: 0, width: 129, height: 47}, 'scroll-01011-8': {x: 1032, y: 0, width: 129, height: 47}, 'scroll-01011-9': {x: 1161, y: 0, width: 129, height: 47}, 'scroll-10000-0': {x: 0, y: 141, width: 129, height: 47}, 'scroll-10000-1': {x: 129, y: 141, width: 129, height: 47}, 'scroll-10000-10': {x: 1290, y: 141, width: 129, height: 47}, 'scroll-10000-11': {x: 1419, y: 141, width: 129, height: 47}, 'scroll-10000-12': {x: 1548, y: 141, width: 129, height: 47}, 'scroll-10000-13': {x: 1677, y: 141, width: 129, height: 47}, 'scroll-10000-14': {x: 1806, y: 141, width: 129, height: 47}, 'scroll-10000-15': {x: 1935, y: 141, width: 129, height: 47}, 'scroll-10000-16': {x: 2064, y: 141, width: 129, height: 47}, 'scroll-10000-17': {x: 2193, y: 141, width: 129, height: 47}, 'scroll-10000-18': {x: 2322, y: 141, width: 129, height: 47}, 'scroll-10000-2': {x: 258, y: 141, width: 129, height: 47}, 'scroll-10000-3': {x: 387, y: 141, width: 129, height: 47}, 'scroll-10000-4': {x: 516, y: 141, width: 129, height: 47}, 'scroll-10000-5': {x: 645, y: 141, width: 129, height: 47}, 'scroll-10000-6': {x: 774, y: 141, width: 129, height: 47}, 'scroll-10000-7': {x: 903, y: 141, width: 129, height: 47}, 'scroll-10000-8': {x: 1032, y: 141, width: 129, height: 47}, 'scroll-10000-9': {x: 1161, y: 141, width: 129, height: 47} }; /** * @type {number} * @const */ turing.deferredsprites.offsets.NUM_SCROLL_FRAMES = 19; /** * @type {number} * @const */ turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME = 9;
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Animates a Turing machine tape. * @author jered@google.com (Jered Wierzbicki) */ goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); goog.provide('turing.Tape'); /** * How many squares of the tape are visible. * Should be odd so that the read/write head is centered. * @type {number} * @const */ turing.NUM_VISIBLE_SQUARES = 9; /** * How many squares of the tape are left of the read/write head. * @type {number} * @const */ turing.NUM_VISIBLE_LEFT_SQUARES = (turing.NUM_VISIBLE_SQUARES - 1) / 2; /** * How many squares of the tape are right of the read/write head and may * scroll into view. Note that this is the number currently visible plus * up to target.length (5) extra squares. This is because when we check for * equality, we start at the beginning of the string and scrollRight until we've * reached the end of the string, possibly revealing an extra 5 squares. * @type {number} * @const */ turing.NUM_VISIBLE_RIGHT_SQUARES = (turing.NUM_VISIBLE_SQUARES - 1) / 2 + 5; /** * Number of extra squares to draw left and right of the fully visible tape * squares. This must be at least two, since we show part of the left neighbor * of the leftmost square while scanning right. * @type {number} * @const */ turing.NUM_MARGIN_SQUARES = 2; /** * How many total squares are on screen, visible or in the margins? * @type {number} * @const */ turing.NUM_SQUARES = turing.NUM_VISIBLE_SQUARES + 2 * turing.NUM_MARGIN_SQUARES; /** * The index of the tape square div under the read/write head when the tape is * stationary. When the tape moves, this div slides left or right, then pops * back into its original position showing a new symbol. * @type {number} * @const */ turing.HEAD_SQUARE = turing.NUM_MARGIN_SQUARES + turing.NUM_VISIBLE_LEFT_SQUARES; /** * Z-index of the tape squares. * @type {number} * @const */ turing.SQUARE_ZINDEX = 400; /** * Left offset for the tape. * @type {number} * @const */ turing.TAPE_LEFT = 63; /** * Top offset for the tape. * @type {number} * @const */ turing.TAPE_TOP = 74; /** * How many pixels of the tape to either side of the visible portion are * partially visible through the slot. * @type {number} * @const */ turing.VISIBLE_FEED_WIDTH = 7; /** * Height of the shadow at the bottom of the tape. * @type {number} * @const */ turing.TAPE_SHADOW_HEIGHT = 4; /** * Duration in ms of scan animation when tape is seeking. * @type {number} * @const */ turing.SEEK_MS = 50; /** * Map from tape symbol to its sprite name. * @type {Object.<string, string>} * @const */ turing.TAPE_SYMBOLS = { '': 'tape_', '_': 'tape_', ' ': 'tape_', '0': 'tape0', '1': 'tape1' }; /** * Sprite sequences to animate symbols being printed. * @type {Object.<string, Array.<string>>} * @const */ turing.PRINT_ANIMATIONS = { '0': ['tape_', 'tape0a', 'tape0b', 'tape0c', 'tape0d', 'tape0'], '1': ['tape_', 'tape1a', 'tape1b', 'tape1c', 'tape1d', 'tape1'] }; /** * Sprite sequences to animate symbols being erased. * @type {Object.<string, Array.<string>>} * @const */ turing.ERASE_ANIMATIONS = { '0': turing.PRINT_ANIMATIONS['0'].slice(0).reverse(), '1': turing.PRINT_ANIMATIONS['1'].slice(0).reverse() }; /** * A Turing machine tape. * @constructor */ turing.Tape = function() { /** * The symbols currently on the tape. * @type {Object.<number, string>} * @private */ this.contents_ = {}; /** * The position of the read/write head. * @type {number} * @private */ this.pos_ = 0; /** * The maximum written tape position. * @type {number} * @private */ this.maxWrittenPosition_ = 0; /** * The location on the tape that the current program started from. * @type {number} * @private */ this.lastStartPos_ = 0; /** * Divs for each visible tape square plus one off each edge. * @type {Array.<Element>} * @private */ this.squares_ = []; /** * A div that holds all the square divs. It is wider than the pane. * @type {Element} * @private */ this.squareHolder_; /** * A div which the square holder moves around inside. * @type {Element} * @private */ this.pane_; /** * A div representing the read/write head. * @type {Element} * @private */ this.readWriteHead_; /** * A div holding the tape squares and head. * @type {Element} * @private */ this.tapeDiv_; /** * A div showing the hole where the left of the tape emerges. * @type {Element} * @private */ this.slotLeft_; /** * A div showing the hole where the right of the tape emerges. * @type {Element} * @private */ this.slotRight_; /** * A div with a shadow to show over the left of the tape. * @type {Element} * @private */ this.shadowLeft_; /** * A div with a shadow to show over the right of the tape. * @type {Element} * @private */ this.shadowRight_; /** * Position currently seeking to, or null if none. * @type {?number} * @private */ this.seekPos_ = null; /** * Is the tape currently scanning left or right? * @type {boolean} * @private */ this.scanning_ = false; }; /** * Attaches tape DOM tree to element. * @param {Element} elem The parent for the tape. */ turing.Tape.prototype.attachTo = function(elem) { this.redrawTape_(); elem.appendChild(this.tapeDiv_); elem.appendChild(this.slotLeft_); elem.appendChild(this.slotRight_); elem.appendChild(this.shadowLeft_); elem.appendChild(this.shadowRight_); }; /** * Create DOM nodes for the tape. */ turing.Tape.prototype.create = function() { var squareSize = turing.sprites.getSize('tape_'); var paneWidth = turing.NUM_VISIBLE_SQUARES * squareSize.width + 2 * turing.VISIBLE_FEED_WIDTH + 2; this.pane_ = turing.sprites.getEmptyDiv(); this.pane_.style.width = paneWidth + 'px'; this.pane_.style.height = squareSize.height + 'px'; this.pane_.style.overflow = 'hidden'; this.pane_.style.left = '0'; this.pane_.style.top = '0'; this.pane_.style.zIndex = turing.SQUARE_ZINDEX; var holderWidth = turing.NUM_SQUARES * squareSize.width; this.squareHolder_ = turing.sprites.getEmptyDiv(); this.squareHolder_.style.width = holderWidth + 'px'; this.squareHolder_.style.left = -turing.NUM_MARGIN_SQUARES * squareSize.width + turing.VISIBLE_FEED_WIDTH + 'px'; // Create visible squares plus extra squares for padding when scrolling. for (var i = 0; i < turing.NUM_SQUARES; i++) { this.squares_[i] = turing.sprites.getDiv('tape_'); this.squares_[i].style.display = 'inline-block'; this.squares_[i].style.position = ''; this.squareHolder_.appendChild(this.squares_[i]); } this.pane_.appendChild(this.squareHolder_); var headSize = turing.sprites.getSize('head'); var extraHeadHeight = headSize.height - squareSize.height; var extraHeadWidth = headSize.width - squareSize.width; this.readWriteHead_ = turing.sprites.getDiv('head'); this.readWriteHead_.style.top = (-extraHeadHeight / 2 - 2) + 'px'; this.readWriteHead_.style.left = turing.VISIBLE_FEED_WIDTH + (turing.NUM_VISIBLE_LEFT_SQUARES * squareSize.width) - extraHeadWidth / 2 + 1 + 'px'; this.readWriteHead_.style.zIndex = turing.SQUARE_ZINDEX + 1; this.tapeDiv_ = turing.sprites.getEmptyDiv(); this.tapeDiv_.style.top = turing.TAPE_TOP + 'px'; this.tapeDiv_.style.left = turing.TAPE_LEFT + 'px'; this.tapeDiv_.appendChild(this.pane_); this.tapeDiv_.appendChild(this.readWriteHead_); this.slotLeft_ = this.createSlot_('slot-left', turing.TAPE_LEFT, -1, squareSize.height); this.slotRight_ = this.createSlot_('slot-right', turing.TAPE_LEFT + paneWidth, 0, squareSize.height); this.shadowLeft_ = this.createShadow_('tape-shadow-l', turing.TAPE_LEFT); this.shadowRight_ = this.createShadow_('tape-shadow-r', turing.TAPE_LEFT + paneWidth - turing.sprites.getSize('tape-shadow-r').width); }; /** * Creates a dom node for a tape slot (a black oval on either side of the tape * where it emerges onto the page). * @param {string} spriteName The sprite to use. * @param {number} leftEdge The left offset of the edge of the tape closest to * this slot. * @param {number} leftBump A small amount by which to move the left coordinate. * Needed because the sizes don't round evenly. * @param {number} squareHeight The height of a tape square. * @return {Element} The slot div. * @private */ turing.Tape.prototype.createSlot_ = function(spriteName, leftEdge, leftBump, squareHeight) { var size = turing.sprites.getSize(spriteName); var slot = turing.sprites.getDiv(spriteName); slot.style.zIndex = turing.SQUARE_ZINDEX - 1; // Behind tape. // On Windows, browsers seem to round 57.5 up to the next pixel right, // which looks wrong, so floor here to match cross platform. slot.style.left = Math.floor(leftEdge - leftBump - size.width / 2) + 'px'; slot.style.top = (turing.TAPE_TOP - turing.TAPE_SHADOW_HEIGHT / 2 + squareHeight / 2 - size.height / 2) + 'px'; return slot; }; /** * Creates a dom node for a tape slot shadow next to the black oval slots. * @param {string} spriteName The sprite to use. * @param {number} leftEdge The left offset of the edge of the tape closest to * this slot. * @return {Element} The slot div. * @private */ turing.Tape.prototype.createShadow_ = function(spriteName, leftEdge) { var slot = turing.sprites.getDiv(spriteName); slot.style.zIndex = turing.SQUARE_ZINDEX + 1; // Above tape. slot.style.left = leftEdge + 'px'; slot.style.top = turing.TAPE_TOP + 'px'; return slot; }; /** * Unbind event listeners, stop timers and tear down DOM. */ turing.Tape.prototype.destroy = function() { for (var i = 0; i < this.squares_.length; i++) { turing.util.removeNode(this.squares_[i]); } this.squares_.splice(0); turing.util.removeNode(this.squareHolder_); this.squareHolder_ = null; turing.util.removeNode(this.pane_); this.pane_ = null; turing.util.removeNode(this.readWriteHead_); this.readWriteHead_ = null; turing.util.removeNode(this.tapeDiv_); this.tapeDiv_ = null; turing.util.removeNode(this.slotLeft_); this.slotLeft_ = null; turing.util.removeNode(this.slotRight_); this.slotRight_ = null; turing.util.removeNode(this.shadowLeft_); this.shadowLeft_ = null; turing.util.removeNode(this.shadowRight_); this.shadowRight_ = null; }; /** * Scrolls the tape to the left. * @param {number} waitTime Delay before scanning starts in ms. * @param {number} scanTime Duration for scan animation in ms. */ turing.Tape.prototype.scanLeft = function(waitTime, scanTime) { this.scanning_ = true; this.pos_--; var squareSize = turing.sprites.getSize('tape_'); var newLeft = -(turing.NUM_MARGIN_SQUARES - 1) * squareSize.width + turing.VISIBLE_FEED_WIDTH; turing.anim.delay(goog.bind(function() { turing.anim.animate(this.squareHolder_, {'left': newLeft + 'px'}, scanTime, goog.bind(this.redrawTape_, this)); }, this), waitTime); }; /** * Scrolls the tape to the right. * @param {number} waitTime Delay before scanning starts in ms. * @param {number} scanTime Duration for scan animation in ms. */ turing.Tape.prototype.scanRight = function(waitTime, scanTime) { this.scanning_ = true; this.pos_++; var squareSize = turing.sprites.getSize('tape_'); var newLeft = -(turing.NUM_MARGIN_SQUARES + 1) * squareSize.width + turing.VISIBLE_FEED_WIDTH; turing.anim.delay(goog.bind(function() { turing.anim.animate(this.squareHolder_, {'left': newLeft + 'px'}, scanTime, goog.bind(this.redrawTape_, this)); }, this), waitTime); }; /** * Scans the tape until it reaches a particular position. This is done by * calling scanLeft/scanRight repeatedly. * @private */ turing.Tape.prototype.seek_ = function() { if (this.seekPos_ == null) { return; } if (this.pos_ < this.seekPos_) { this.scanRight(0, turing.SEEK_MS); } else if (this.pos_ > this.seekPos_) { this.scanLeft(0, turing.SEEK_MS); } else { // We've arrived at the seek position. Nuke everything except the currently // visible portion of the tape. this.seekPos_ = null; this.clearOutsideRange_( this.pos_ - turing.NUM_VISIBLE_LEFT_SQUARES, this.pos_ + turing.NUM_VISIBLE_RIGHT_SQUARES); } }; /** * Clears tape squares not in the range [start, end]. * @param {number} start The position of the first square to keep. * @param {number} end The position of the last square to keep. * @private */ turing.Tape.prototype.clearOutsideRange_ = function(start, end) { for (var i in this.contents_) { i = /** @type {number} */(i); // Reassure the compiler. if (i < start || i > end) { this.contents_[i] = ''; } } }; /** * Prints a symbol at the read/write head position. * @param {string} symbol Symbol to print. * @param {number} eraseTime Duration in ms for erasing old symbol. * @param {number} printTime Duration in ms for printing new symbol. */ turing.Tape.prototype.print = function(symbol, eraseTime, printTime) { var oldSymbol = this.contents_[this.pos_]; this.contents_[this.pos_] = symbol; this.maxWrittenPosition_ = Math.max(this.pos_, this.maxWrittenPosition_); // Always erase the old symbol and then print a new symbol, instead of // animating changing a 0 directly to a 1 or vice versa. this.showErase_(oldSymbol, eraseTime, goog.bind(this.showPrint_, this, symbol, printTime)); }; /** * Shows a symbol being erased from the tape. * @param {string} symbol The symbol to erase. * @param {number} time Duration in ms for erasing animation. * @param {function()} onDone Function to call when done erasing. * @private */ turing.Tape.prototype.showErase_ = function(symbol, time, onDone) { if (symbol == '0' || symbol == '1') { turing.anim.animateFromSprites(this.squares_[turing.HEAD_SQUARE], turing.ERASE_ANIMATIONS[symbol], time, onDone); } else { // Square is already blank. Delay before calling onDone anyway so that // there is a pause between when a print operation circle is lit and when we // show a symbol being printed. turing.anim.delay(onDone, time); } }; /** * Shows a symbol being printed on the tape. * @param {string} symbol The symbol to print. * @param {number} time Duration in ms for printing animation. * @private */ turing.Tape.prototype.showPrint_ = function(symbol, time) { if (symbol == '0' || symbol == '1') { turing.anim.animateFromSprites(this.squares_[turing.HEAD_SQUARE], turing.PRINT_ANIMATIONS[symbol], time, goog.bind(this.redrawSquare_, this, turing.HEAD_SQUARE)); } // Otherwise, assume square has already been erased by showErase_. }; /** * Gets the symbol under the read/write head. * @return {string} The symbol, or '_' if none. */ turing.Tape.prototype.getCurSymbol = function() { return this.contents_[this.pos_] || '_'; }; /** * Appends a string one visible tape width past the last written position on * the tape and scans to there. Used to set up initial tape for a program after * another program has been running for a while. * @param {string} str The desired initial contents of the tape. */ turing.Tape.prototype.setString = function(str) { this.maxWrittenPosition_ += turing.NUM_SQUARES; var start = this.maxWrittenPosition_; // Save this start position so we can reset to the same string if this next // program run is not correct. this.lastStartPos_ = start; this.writeString_(str, start); // We wrote str.length more characters. this.maxWrittenPosition += str.length; this.reinitializePositionOnTape_(str, start); }; /** * Similar to setString but resets to the last program start in-place. * @param {string} str The desired initial contents of the tape. */ turing.Tape.prototype.resetString = function(str) { var start = this.lastStartPos_; this.writeString_(str, start); // Clear everything to the left or right of the string. this.clearOutsideRange_(start, start + str.length - 1); this.reinitializePositionOnTape_(str, start); }; /** * Write the given string to the tape. * @param {string} str The desired contents of the tape. * @param {number} start The position to start writing the string on the tape. * @private */ turing.Tape.prototype.writeString_ = function(str, start) { // Reset the symbols on the tape. for (var i = 0; i < str.length; i++) { this.contents_[start + i] = str.charAt(i); } }; /** * Move to the middle of the current string on the tape. * @param {string} str The current string on the tape. * @param {number} start The start position of the current string on the tape. * @private */ turing.Tape.prototype.reinitializePositionOnTape_ = function(str, start) { this.seekPos_ = start + Math.floor(str.length / 2); if (!this.scanning_) { // If the tape is already scanning, redrawTape will get called when that // animation finishes, and will call seek_ to scan. this.redrawTape_(); } }; /** * @return {number} The index of the first symbol on the tape. * @private */ turing.Tape.prototype.getIndexOfFirstSymbol_ = function() { var minValidPos = null; for (var i in this.contents_) { i = /** @type {number} */(i); // Reassure the compiler. if (this.contents_[i] && this.contents_[i] != '_' && this.contents_[i] != ' ') { if (minValidPos == null) { minValidPos = i; } minValidPos = Math.min(minValidPos, i); } } if (minValidPos == null) { return -1; } return minValidPos; }; /** * Trigger a scan to the square that's offset spaces from the beginning of the * string on the tape and return the contents of that square. * @param {number} offset The number of spaces from the beginning of the string. * @return {string} The contents of the square or the empty string. */ turing.Tape.prototype.scanToAndGetSymbol = function(offset) { var index = this.getIndexOfFirstSymbol_() + offset; if (index == -1) { return ''; } this.seekPos_ = index; this.seek_(); return this.contents_[index]; }; /** * Updates the visible portion of the tape. * @private */ turing.Tape.prototype.redrawTape_ = function() { this.scanning_ = false; var squareSize = turing.sprites.getSize('tape_'); // Also set up the invisible squares just off the edges of the tape. for (var i = 0; i < turing.NUM_SQUARES; i++) { this.redrawSquare_(i); } this.squareHolder_.style.left = -turing.NUM_MARGIN_SQUARES * squareSize.width + turing.VISIBLE_FEED_WIDTH + 'px'; this.seek_(); }; /** * Redraws one square on the tape. * @param {number} i Index among _drawn_ squares. * @private */ turing.Tape.prototype.redrawSquare_ = function(i) { var offs = (i + this.pos_) - turing.HEAD_SQUARE; var symbol = this.contents_[offs] || ''; var spriteName = turing.TAPE_SYMBOLS[symbol]; this.squares_[i].style.background = turing.sprites.getBackground(spriteName); }; /** * Slides the entire tape assembly up to the top of the display area. * Used to make room for larger programs in bonus mode. */ turing.Tape.prototype.slideUp = function() { // 7px from the bottom of the tooltip. turing.anim.animate(this.tapeDiv_, {'top': '27px'}, 200); turing.anim.animate(this.shadowLeft_, {'top': '27px'}, 200); turing.anim.animate(this.shadowRight_, {'top': '27px'}, 200); turing.anim.animate(this.slotLeft_, {'top': '21px'}, 200); turing.anim.animate(this.slotRight_, {'top': '21px'}, 200); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Offsets for the number plate sprite. * @author corrieann@google.com (Corrie Scalisi) */ goog.provide('turing.sprites.numberplate'); goog.require('turing.sprites'); goog.require('turing.sprites.offsets'); /** * The width of the number plate. * @type {number} * @const * @private */ turing.sprites.numberplate.WIDTH_ = 129; /** * Gets the CSS background for the given unlit number plate. * @param {string} target The target. * @return {string} The CSS background string. */ turing.sprites.numberplate.getUnlitNumberPlate = function(target) { return turing.sprites.getBackground('light-' + target + '-0'); }; /** * Return the background for the given number target and digit combination. * If the length of the target (5) is passed in, then the sprite representing * the entire string will be returned. * @param {string} target The target. * @param {number} digit The digit we care about right now. * @param {boolean} fullyLit Whether the digit should be fully lit. * @return {string} The CSS background string. */ turing.sprites.numberplate.getLitTargetForDigit = function( target, digit, fullyLit) { // The column number of the unlit version of that digit. // We always add at least 1 because the first column has no digits lit. var digitXOffset = digit * 2 + (fullyLit ? 2 : 1); return turing.sprites.getBackground('light-' + target + '-' + digitXOffset); }; /** * Get an array of backgrounds used to animate scrolling of the given target. * Grabs the first one from the main sprite and triggers a load of the sprites * with the other number plates. * @param {string} target The target. * @param {boolean} scrollIn Whether the target should scroll in, scrolls out if * false. * @return {Array.<string>} The CSS backgrounds. */ turing.sprites.numberplate.getScrollingTarget = function(target, scrollIn) { var backgrounds = []; for (var i = 0; i <= turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME; i++) { var col = scrollIn ? i : turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME + i; backgrounds.push(turing.sprites.getBackground( 'scroll-' + target + '-' + col)); } return backgrounds; };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Simulates a Turing machine program running. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Simulator'); goog.require('turing.Program'); goog.require('turing.Tape'); goog.require('turing.anim'); /** * Speed settings the simulator can run at. * @enum {number} */ turing.SpeedSetting = { SLOW: 0, TUTORIAL: 1, NORMAL: 2, FAST: 3, LUDICROUS: 4 }; /** * Configuration for a simulator speed setting. * - stepTime: ms between simulation steps that do something. * - emptyStepTime: ms between no-op steps. * - tapeTime: ms for a tape operation. * - branchTime: ms for a branch operation. * @typedef {{stepTime: number, tapeTime: number, emptyStepTime: number, * branchTime: number}} * @private */ turing.Speeds; /** * The definitions for speed settings. * @type {Object.<turing.SpeedSetting, turing.Speeds>} * @const */ turing.SPEED_CONFIG = { 0 /* SLOW */: { stepTime: 750, tapeTime: 600, emptyStepTime: 400, branchTime: 850 }, 1 /* TUTORIAL */: { stepTime: 650, tapeTime: 500, emptyStepTime: 200, branchTime: 750 }, 2 /* NORMAL */: { stepTime: 450, tapeTime: 300, emptyStepTime: 200, branchTime: 550 }, 3 /* FAST */: { stepTime: 250, tapeTime: 200, emptyStepTime: 100, branchTime: 250 }, 4 /* LUDICROUS */: { stepTime: 100, tapeTime: 50, emptyStepTime: 100, branchTime: 100 } }; /** * How many times an operation can be repeated before it gets somewhat boring. * @type {number} * @const */ turing.SOMEWHAT_BORING_REPEAT_COUNT = 4; /** * How many times an operation can be repeated before it gets very boring. * @type {number} * @const */ turing.VERY_BORING_REPEAT_COUNT = 6; /** * Simulates programs. * @constructor */ turing.Simulator = function() { /** * The currently running program. * @type {turing.Program} * @private */ this.program_ = null; /** * The currently simulating tape. * @type {turing.Tape} * @private */ this.tape_ = null; /** * The id of the timeout which will step the program forward one step. * @type {number} * @private */ this.stepTimerId_ = -1; /** * Function to call when the program is done. * @type {?function()} * @private */ this.doneCallback_ = null; /** * Steps this program has run. * @type {number} * @private */ this.stepCount_ = 0; /** * Steps the program may run before we terminate it. * @type {number} * @private */ this.stepLimit_ = 0; /** * Maps from program locations to how many time operations at that location * have been run. * @type {Object.<string, number>} * @private */ this.runCount_ = {}; /** * How fast the simulation is going. * @type {turing.Speeds} * @private */ this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.NORMAL]; /** * True iff simulation is currently paused. * @type {boolean} * @private */ this.paused_ = false; }; /** * Returns whether the simulator is stepping the program. * @return {boolean} True iff the program is currently running. */ turing.Simulator.prototype.isRunning = function() { return this.stepTimerId_ != -1; }; /** * Sets a limit for the number of steps a program may execute. * @param {number} limit The number of steps, or 0 for no limit. */ turing.Simulator.prototype.setStepLimit = function(limit) { this.stepLimit_ = limit; }; /** * Used to check if the simulator will run until explicitly stopped, which is * the case in demo mode and when showing the bonus program. * @return {boolean} True iff the simulator has a step limit, false if it may * run forever. */ turing.Simulator.prototype.hasStepLimit = function() { return this.stepLimit_ != 0; }; /** * Starts running a program. * @param {turing.Program} program Program to run. * @param {turing.Tape} tape Tape for I/O. * @param {turing.SpeedSetting} speed How fast to run. * @param {function()=} opt_doneCallback Function to call when program halts or * times out. */ turing.Simulator.prototype.run = function(program, tape, speed, opt_doneCallback) { if (this.isRunning()) { return; } // Start at the first instruction. program.setNextPos(0, 0); this.speeds_ = turing.SPEED_CONFIG[speed]; this.stepCount_ = 0; this.runCount_ = {}; this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), 0); this.program_ = program; this.tape_ = tape; this.doneCallback_ = opt_doneCallback || null; }; /** * Immediately stops running the current program, if running. */ turing.Simulator.prototype.stop = function() { if (this.stepTimerId_ != -1) { turing.anim.cancel(this.stepTimerId_); } this.stepTimerId_ = -1; this.program_ = null; this.tape_ = null; if (this.doneCallback_) { this.doneCallback_(); this.doneCallback_ = null; } }; /** * Pauses simulation: cancels the next step call, but does not reset any state. */ turing.Simulator.prototype.pause = function() { if (this.stepTimerId_ != -1) { turing.anim.cancel(this.stepTimerId_); } this.stepTimerId_ = -1; this.paused_ = true; }; /** * Resumes simulation at the next step. */ turing.Simulator.prototype.resumeIfPaused = function() { if (this.paused_) { this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), 0); } this.paused_ = false; }; /** * Advances program simulation by one step. */ turing.Simulator.prototype.step = function() { if (!this.tape_ || !this.program_ || this.stepTimerId_ == -1) { return; } this.stepTimerId_ = -1; // Dim the current instruction and highlight the next (if not at end). Note // that this only changes the value of the current pos, not the next pos; // the next pos here is set by setNextPos from the previous call. this.program_.goToNextPos(); if (this.program_.isNextPosEnd() || (this.stepLimit_ > 0 && this.stepCount_ > this.stepLimit_)) { // Simulation stops when we try to move to an invalid position or run for // more than a maximum number of steps. // We must explicitly dim the current lit up op in case we exceeded the step // count (the Program object doesn't know this, so it will still be lit // after the goToNextPos call above.) this.program_.dimCurOp(); this.stop(); return; } if (this.stepLimit_ > 0) { // Only accelerate boring loops when they might be unintentional infinite // loops (i.e., when a step limit is set). this.speedUpBoringLoops_(); } this.stepCount_++; var op = this.program_.getCurOp(); if (op && op.charAt(0) == '*') { op = op.substr(1); } var implicitStep = true; // Most ops implicitly step one position. // Tape ops update tape state immediately, but take speeds_.tapeTime ms // to animate. Spend half the total animation time setting up (erasing before // printing or delaying before moving) and the other half animating, so that // there's a delay between when the op is lit and when it seems to happen. var tapeWaitTime = this.speeds_.tapeTime / 2; var tapeExecuteTime = this.speeds_.tapeTime / 2; if (op == '0' || op == '1' || op == '_') { this.tape_.print(op, tapeWaitTime, tapeExecuteTime); } else if (op == 'L') { this.tape_.scanLeft(tapeWaitTime, tapeExecuteTime); } else if (op == 'R') { this.tape_.scanRight(tapeWaitTime, tapeExecuteTime); } else if (/B[2-9]/.test(op)) { // Regexp matches a B followed by a digit from 2 to 9, which are allowable // branch offsets. Normal game programs only use B2-4, but our bonus program // needs longer branch offsets. this.program_.setNextPos(this.program_.getCurTrack(), this.program_.getCurTrackPos() - parseInt(op.charAt(1), 10)); implicitStep = false; } else if (/^D/.test(op)) { // 'Dx' jumps down one track if the current symbol is 'x'. 'D' by itself // jumps down unconditionally. if (op.length == 1 || this.tape_.getCurSymbol() == op.charAt(1)) { this.program_.setNextPos(this.program_.getCurTrack() + 1, this.program_.getCurTrackPos()); implicitStep = false; } } else if (/^U/.test(op)) { // 'Ux' jumps up one track if the current symbol is 'x'. 'U' by itself jumps // up unconditionally. if (op.length == 1 || this.tape_.getCurSymbol() == op.charAt(1)) { this.program_.setNextPos(this.program_.getCurTrack() - 1, this.program_.getCurTrackPos()); implicitStep = false; } } if (implicitStep) { this.program_.setNextPos(this.program_.getCurTrack(), this.program_.getCurTrackPos() + 1); } var stepTime = this.speeds_.stepTime; if (!op) { stepTime = this.speeds_.emptyStepTime; } else if (/^[UDB]/.test(op)) { // /^[UDB]/ matches a U, D or B at the start of op, which are branch // operations. stepTime = this.speeds_.branchTime; } this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), stepTime); }; /** * Detects if the program has gotten stuck in a boring loop, and speeds up if * so. A loop is "somewhat boring" when the same operation has been repeated * more than 4 times (since game programs are only supposed to change 5 squares * on the tape, this is about right), and "very boring" when it has been * repeated more than 6 times. This speed boost only applies to the current * run() call, and speeds and operation run counts are reset at the beginning of * the next run. * @private */ turing.Simulator.prototype.speedUpBoringLoops_ = function() { var pc = this.program_.getCurTrack() + ',' + this.program_.getCurTrackPos(); var count = this.runCount_[pc] || 0; this.runCount_[pc] = count + 1; if (count > turing.VERY_BORING_REPEAT_COUNT) { // We have to go straight to ludicrous speed. this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.LUDICROUS]; } else if (count > turing.SOMEWHAT_BORING_REPEAT_COUNT) { // This is getting boring, speed it up. this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.FAST]; } };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Samples points on cubic Bézier curves. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.CubicBezier'); /** * How many points to pre-compute for evaluating curves. * This can be a fairly low number, since a 1 second animation at 60Hz will * update only about 60 times, and most of our animations are short. * @type {number} * @const */ turing.BEZIER_SAMPLES = 120; /** * The resolution for numerically solving the "x" polynomial when sampling. * I picked this value by staring at curves until they looked smooth. * @type {number} * @const */ turing.BEZIER_EPSILON = 0.0001; /** * How to evaluate curves. Different platforms have widely varying floating * point and Javascript performance. Here are times (in us) for some different * platforms for each of these methods: * Platform Solve Linear Nearest * MacBook Pro 150 88 18 * iPad1 3939 1258 692 * Nexus S 1074 616 252 * @enum {number} */ turing.BezierEvaluation = { SOLVE: 0, NEAREST_INTERP: 1, LINEAR_INTERP: 2 }; /** * Evaluates a cubic Bézier curve, * B(t) = (1-t)^3 P0 + 3(1-t)^2 t P1 + 3(1-t) t^2 P2 + t^3 P3, t in [0,1], * at positions x in [0,1] given P0=(0,0), P3=(1,1), and P1 and P2 specified. * Used for animation timing in browsers that do not support CSS transitions. * Based on WebKit: * trac.webkit.org/browser/trunk/Source/WebCore/platform/graphics/UnitBezier.h * @param {number} p1x x-coordinate of P1. * @param {number} p1y y-coordinate of P1. * @param {number} p2x x-coordinate of P2. * @param {number} p2y y-coordinate of P2. * @param {turing.BezierEvaluation} evalMode How to evaluate. * @constructor */ turing.CubicBezier = function(p1x, p1y, p2x, p2y, evalMode) { /** * Coefficients of the x polynomial. * @type {Array.<number>} * @private */ this.xCoefs_ = this.getCoefs_(p1x, p2x); /** * Coefficients of the y polynomial. * @type {Array.<number>} * @private */ this.yCoefs_ = this.getCoefs_(p1y, p2y); /** * How to evaluate the curve. * @type {turing.BezierEvaluation} * @private */ this.evalMode_ = evalMode; /** * Sampled points on the curve. * @type {Array.<number>} * @private */ this.samples_ = this.evalMode_ != turing.BezierEvaluation.SOLVE ? this.precompute_() : []; }; /** * Converts parametric form to an explicit polynomial. * @param {number} p1 The first parameteric point. * @param {number} p2 The second parameteric point. * @return {Array.<number>} Coefficients for an explicit polynomial. * @private */ turing.CubicBezier.prototype.getCoefs_ = function(p1, p2) { var c = 3 * p1; var b = 3 * (p2 - p1) - c; var a = 1 - c - b; return [a, b, c]; }; /** * Precomputes a table of (x, y) positions on the curve. * @return {Array.<number>} y coordinates on the curve for x positions in [0,1], * with indices of x * BEZIER_SAMPLES. * @private */ turing.CubicBezier.prototype.precompute_ = function() { var samples = []; for (var i = 0; i < turing.BEZIER_SAMPLES; i++) { var x = i / turing.BEZIER_SAMPLES; samples[i] = this.evaluate_(this.yCoefs_, this.solve_(x)); } return samples; }; /** * Samples the curve. * @param {number} x The x value to evaluate. * @return {number} The y value near there. */ turing.CubicBezier.prototype.sample = function(x) { if (this.evalMode_ == turing.BezierEvaluation.NEAREST_INTERP) { return this.sampleNearest_(x); } else if (this.evalMode_ == turing.BezierEvaluation.LINEAR_INTERP) { return this.sampleLinear_(x); } else { return this.evaluate_(this.yCoefs_, this.solve_(x)); } }; /** * Picks the nearest precomputed sample to get the y value of the curve near x * in [0,1]. * @param {number} x The x value to evaluate. * @return {number} The y value near there. * @private */ turing.CubicBezier.prototype.sampleNearest_ = function(x) { var s = Math.floor(x * turing.BEZIER_SAMPLES); return s < 0 ? 0 : (s >= turing.BEZIER_SAMPLES ? 1 : this.samples_[s]); }; /** * Uses linear interpolation between precomputed samples to get the y value of * the curve near x in [0,1]. * @param {number} x The x value to evaluate. * @return {number} The y value near there. * @private */ turing.CubicBezier.prototype.sampleLinear_ = function(x) { var s = x * turing.BEZIER_SAMPLES; // The sample number. var sLeft = Math.floor(s); var sRight = Math.ceil(s); if (sLeft < 0) { // x < 0: The leftmost point is fixed at (0,0). return 0; } else if (sLeft >= turing.BEZIER_SAMPLES) { // x >= 1: The rightmost point is fixed at (1,1). return 1; } else if (sLeft == sRight) { // x is exactly on a sample. return this.samples_[sLeft]; } else { // Linearly interpolate between the nearest samples to x. return ((sRight - s) * this.samples_[sLeft] + (s - sLeft) * this.samples_[sRight]); } }; /** * Evaluates a t^3 + b t^2 + c t expanded using Horner's rule. * @param {Array.<number>} coefs Coefficients [a, b, c]. * @param {number} t Input for polynmoial. * @return {number} The value of the polynomial. * @private */ turing.CubicBezier.prototype.evaluate_ = function(coefs, t) { return ((coefs[0] * t + coefs[1]) * t + coefs[2]) * t; }; /** * Evaluates the derivative of a t^3 + b t^2 + c t. * @param {Array.<number>} coefs Coefficients [a, b, c]. * @param {number} t Input for polynmoial. * @return {number} The value of the derivative polynomial. * @private */ turing.CubicBezier.prototype.evaluateDerivative_ = function(coefs, t) { return (3 * coefs[0] * t + 2 * coefs[1]) * t + coefs[2]; }; /** * Solves a t^3 + b t^2 + c t = x for t. * @param {number} x x position to solve for. * @return {number} The t (parameter) value corresponding to a given x. * @private */ turing.CubicBezier.prototype.solve_ = function(x) { var t0; var t1; var t2; var x2; var d2; var i; // First try a few iterations of Newton's method -- normally very fast. for (t2 = x, i = 0; i < 8; i++) { x2 = this.evaluate_(this.xCoefs_, t2) - x; if (Math.abs(x2) < turing.BEZIER_EPSILON) { return t2; } d2 = this.evaluateDerivative_(this.xCoefs_, t2); if (Math.abs(d2) < 1e-6) { break; } t2 = t2 - x2 / d2; } // Fall back to the bisection method for reliability. t0 = 0.0; t1 = 1.0; t2 = x; if (t2 < t0) { return t0; } if (t2 > t1) { return t1; } while (t0 < t1) { x2 = this.evaluate_(this.xCoefs_, t2); if (Math.abs(x2 - x) < turing.BEZIER_EPSILON) { return t2; } if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) * .5 + t0; } // Failure. return t2; };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview A clickable overlay covering the entire doodle area. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Overlay'); goog.require('turing.sprites'); goog.require('turing.util'); /** * The z-index for the overlay div. Should be on top of everything else. * @type {number} * @const */ turing.OVERLAY_ZINDEX = 500; /** * An invisible div on top of the doodle in its passive mode. * @constructor */ turing.Overlay = function() { /** * An empty div element which fills its parent. * @type {Element} * @private */ this.div_; /** * Event listener for clicks. * @type {?function()} * @private */ this.clickHandler_; /** * Called to report a click to an observer. * @type {function()} * @private */ this.callback_; }; /** * Creates overlay div and registers a click event listener on it. * @param {Element} logoContainer Element to overlay; used for sizing. */ turing.Overlay.prototype.create = function(logoContainer) { this.div_ = turing.sprites.getEmptyDiv(); this.div_.style.width = logoContainer.offsetWidth + 'px'; this.div_.style.height = logoContainer.offsetHeight + 'px'; this.div_.style.cursor = 'pointer'; this.div_.style.zIndex = turing.OVERLAY_ZINDEX; this.clickHandler_ = goog.bind(this.onClick, this); turing.util.listen(this.div_, 'click', this.clickHandler_); }; /** * Destroys dom elements and cleans up event listeners. */ turing.Overlay.prototype.destroy = function() { turing.util.unlisten(this.div_, 'click', this.clickHandler_); turing.util.removeNode(this.div_); this.clickHandler_ = null; this.div_ = null; }; /** * Attaches to dom and sets click action. * @param {Element} elem Parent. * @param {function()} callback Called on a click. */ turing.Overlay.prototype.attachTo = function(elem, callback) { elem.appendChild(this.div_); this.callback_ = callback; }; /** * Event listener for clicks on the overlay. */ turing.Overlay.prototype.onClick = function() { this.destroy(); this.callback_(); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Lightweight helper library for animation. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); /** * Iff true, do not schedule any more animations. * @type {boolean} * @private */ turing.anim.stopped_ = true; /** * A list of pending animation frames. * @type {Array.<Object>} * @private */ turing.anim.queue_ = []; /** * True iff there were more frames queued this tick and the queue needs to be * resorted. * @type {boolean} * @private */ turing.anim.queueDirty_ = false; /** * The current animation tick. * @type {number} * @private */ turing.anim.curTick_ = 0; /** * The next event id. * @private * @type {number} */ turing.anim.eventId_ = 1; /** * The time when the last animation tick started. * @type {number} * @private */ turing.anim.lastTickStartTime_ = 0; /** * A count of recent ticks which were were longer than the current target. * @type {number} * @private */ turing.anim.tooSlowTicks_ = 0; /** * Inverse of the maximum frame rate (60 Hz). * @type {number} * @private * @const */ turing.anim.MAX_FPS_MS_ = 1000 / 60; /** * Inverse of the minimum frame rate (20 Hz). * The game is functional, but really laggy to play below this frame rate. We'll * never schedule animations slower than this. * @type {number} * @private * @const */ turing.anim.MIN_FPS_MS_ = 1000 / 20; /** * The interval at which the next frame will be rescheduled. This is controlled * by throttleFrameRate_. * @type {number} * @private */ turing.anim.msPerFrame_ = turing.anim.MAX_FPS_MS_; /** * The name of the CSS3 transition property, or undefined if transitions are * unsupported. * @type {string|undefined} * @private */ turing.anim.transitionPropertyName_ = turing.util.getVendorCssPropertyName( 'transition'); /** * Map from CSS properties we know how to animate to the units we expect will be * attached. Used to trim units off and add them back when interpolating values. * @type {Object.<string, string>} */ turing.anim.UNITS = { 'top': 'px', 'left': 'px' }; /** * How to schedule the next animation frame. * @type {function(function())} */ window['requestAnimationFrame'] = (function() { return window['requestAnimationFrame'] || window['webkitRequestAnimationFrame'] || window['mozRequestAnimationFrame'] || window['oRequestAnimationFrame'] || window['msRequestAnimationFrame'] || function(callback) { // Binding this on window because Chrome gets cross if we do not. // If we have nothing better, just do a setTimeout; the caller should be // careful to check turing.anim.stopped_. It is not checked here because // it'd be weird to export that behavior. window.setTimeout(callback, turing.anim.msPerFrame_); }; })(); /** * @param {number} duration A duration in ms. * @return {number} The corresponding number of ticks at the current frame rate. * @private */ turing.anim.getNumTicks_ = function(duration) { return Math.ceil(duration / turing.anim.msPerFrame_); }; /** * Schedules callback to be run after a duration in ms. * @param {function()} callback The function to call when delay is elapsed. * @param {number} duration How long to wait in ms. * @return {number} An id for the event to be delayed. */ turing.anim.delay = function(callback, duration) { // Count ticks to wait based on the current frame rate. return turing.anim.delayTicks(callback, turing.anim.getNumTicks_(duration)); }; /** * Schedules callback to be run after a duration in animation ticks. * @param {function()} callback The function to call when delay is elapsed. * @param {number} ticksToWait How long to wait in animation loop ticks. * @return {number} An id for the event to be delayed. */ turing.anim.delayTicks = function(callback, ticksToWait) { var eventId = turing.anim.eventId_++; turing.anim.queue_.push({ ticks: turing.anim.curTick_ + ticksToWait, call: callback, eventId: eventId }); turing.anim.queueDirty_ = true; return eventId; }; /** * Cancels a pending event previously scheduled with some delay. * @param {number} eventId The id of the event in the animation queue. */ turing.anim.cancel = function(eventId) { for (var i = 0; i < turing.anim.queue_.length; i++) { if (turing.anim.queue_[i].eventId == eventId) { turing.anim.queue_.splice(i, 1); return; } } }; /** * Animates CSS properties on an element. * @param {Element} elem The element to animate. * @param {Object.<string, string>} properties CSS property names -> new values. * @param {number} duration How long the animation should run. * @param {function()=} opt_doneCallback Called when animation is done. */ turing.anim.animate = function(elem, properties, duration, opt_doneCallback) { var initialValue = {}; var finalValue = {}; for (var name in properties) { initialValue[name] = parseFloat(elem.style[name] || 0); finalValue[name] = parseFloat(properties[name]); } // Schedule ticks based on the current frame rate. var numTicks = turing.anim.getNumTicks_(duration); for (var tick = 0; tick <= numTicks; tick++) { var progress = Math.min(1, tick / numTicks); for (var name in properties) { turing.anim.delayTicks(goog.bind(function(progress) { var interp = (1 - progress) * initialValue[name] + progress * finalValue[name]; var value = interp + (turing.anim.UNITS[name] || ''); elem.style[name] = value; }, window, progress), tick); } } if (opt_doneCallback) { turing.anim.delayTicks(opt_doneCallback, numTicks); } }; /** * Sets the CSS3 transition property for an element or does nothing if * transitions aren't supported. * @param {Element} elem The element to set transition for. * @param {string} transitionValue The css value for transition. */ turing.anim.setTransitionStyle = function(elem, transitionValue) { if (turing.anim.transitionPropertyName_) { elem.style[turing.anim.transitionPropertyName_] = transitionValue; } }; /** * Clears CSS3 transitions on elem. * @param {Element} elem The element to clear transitions for. */ turing.anim.clearTransitionStyle = function(elem) { // Opera doesn't seem to completely support removing an animation // (setting it to 'none' still causes a delay when changing the left // offset), so instead set a dummy property to animate for. turing.anim.setTransitionStyle(elem, 'clear 0ms linear'); }; /** * Animates changing the sprite used for an element background. Goes through * the background list, retrieving the sprite background, and then calls * animateThroughBackgrounds. * @param {Element} elem The element to animate. * @param {Array.<string>} spriteNames The names of the desired elements in the * sprite to iterate through. * @param {number} duration How long the animation should run. * @param {function()=} opt_doneCallback Called when animation is done. */ turing.anim.animateFromSprites = function(elem, spriteNames, duration, opt_doneCallback) { var backgrounds = []; for (var i = 0; i < spriteNames.length; i++) { backgrounds[i] = turing.sprites.getBackground(spriteNames[i]); } turing.anim.animateThroughBackgrounds( elem, backgrounds, duration, opt_doneCallback); }; /** * Animates changing the backgrounds of an element. * @param {Element} elem The element to animate. * @param {Array.<string>} backgrounds The CSS backgrounds to iterate through. * @param {number} duration How long the animation should run. * @param {function()=} opt_doneCallback Called when animation is done. */ turing.anim.animateThroughBackgrounds = function(elem, backgrounds, duration, opt_doneCallback) { // Schedule ticks based on the current frame rate. var numTicks = turing.anim.getNumTicks_(duration); for (var tick = 0; tick <= numTicks; tick++) { var progress = Math.min(1, tick / numTicks); turing.anim.delayTicks(goog.bind(function(progress) { elem.style.background = backgrounds[ Math.min(backgrounds.length - 1, Math.floor(progress * backgrounds.length))]; }, window, progress), tick); } if (opt_doneCallback) { turing.anim.delayTicks(opt_doneCallback, numTicks); } }; /** * A monolithic animation loop implemented using requestAnimationFrame. At each * tick, it runs any functions deferred til this tick. * * All deferred calls are scheduled to run from this loop so that the game * simulation and animation update synchronously without being explicitly * stitched together through callbacks everywhere. * * We also tried an asynchronous approach, using CSS3 transitions and * requestAnimationFrame to update animations and separate setTimeout calls to * run the game. This performed better, but degraded poorly; there were odd * skips in animation, and weird behavior when changing browser tabs since * requestAnimationFrame and setTimeout turn down differently. With this * approach, the game slows down uniformly under load. * * @private */ turing.anim.loop_ = function() { window.requestAnimationFrame(function step() { if (turing.anim.stopped_) { return; } // Note we must do this even when using requestAnimationFrame, because it // isn't 60 Hz everywhere, and we may need to throttle down to its actual // rate for our delays to make sense. turing.anim.throttleFrameRate_(); if (turing.anim.queueDirty_) { // We'd like to keep frames in a priority queue but don't want to bother, // so just sort the frame queue when it changes. turing.anim.queue_.sort(function(a, b) { if (a.ticks == b.ticks) { // Guarantee the sort is stable. return a.eventId - b.eventId; } return a.ticks - b.ticks; }); turing.anim.queueDirty_ = false; } var numFrames = 0; for (var i = 0, frame; frame = turing.anim.queue_[i]; i++) { if (frame.ticks <= turing.anim.curTick_) { frame.call(); numFrames++; } else { break; } } turing.anim.queue_.splice(0, numFrames); turing.anim.curTick_++; window.requestAnimationFrame(step); }); }; /** * Measures and controls the interval between frames. * @private */ turing.anim.throttleFrameRate_ = function() { var tickStartTime = new Date().getTime(); // At the start of the doodle, wait until things stabilize a bit (i.e. the // page finishes loading) before throttling the frame rate. Arbitrarily guess // this happens after 30 frames (which is nominally ~0.5 seconds). // Also check that lastTickStartTime is non-zero, since it will be reset to // zero if the animation loop is stopped for any reason (and then tickLength // below would be invalid). if (turing.anim.curTick_ > 30 && turing.anim.lastTickStartTime_) { var tickLength = tickStartTime - turing.anim.lastTickStartTime_; if (tickLength >= 1.05 * turing.anim.msPerFrame_) { // The last tick was too slow. turing.anim.tooSlowTicks_++; } else { // The last tick was within tolerance. turing.anim.tooSlowTicks_ = turing.anim.tooSlowTicks_ >> 1; } if (turing.anim.tooSlowTicks_ > 20) { // Animation consistently isn't making our target frame rate; slow down // frame rate by 20% up to a minimum frame rate. turing.anim.msPerFrame_ = Math.min(turing.anim.MIN_FPS_MS_, turing.anim.msPerFrame_ * 1.2); turing.anim.tooSlowTicks_ = 0; } } turing.anim.lastTickStartTime_ = tickStartTime; }; /** * Start animation loop. */ turing.anim.start = function() { turing.anim.stopped_ = false; turing.anim.loop_(); }; /** * Resets controller state for frames-per-second throttling. * @private */ turing.anim.resetFpsController_ = function() { turing.anim.tooSlowTicks_ = 0; // Wait for a tick before measuring the interval between two ticks. turing.anim.lastTickStartTime_ = 0; }; /** * Emergency brake; stop animation loop next time through. */ turing.anim.stop = function() { turing.anim.stopped_ = true; turing.anim.resetFpsController_(); }; /** * Stops the animation loop and cancels any queued animations. */ turing.anim.reset = function() { turing.anim.stop(); turing.anim.queue_ = []; turing.anim.curTick_ = 0; turing.anim.queueDirty_ = false; turing.anim.eventId_ = 1; turing.anim.msPerFrame_ = turing.anim.MAX_FPS_MS_; turing.anim.resetFpsController_(); }; /** * @return {boolean} True iff animations are stopped. */ turing.anim.isStopped = function() { return turing.anim.stopped_; };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Shows Turing machine programs as rows of operations. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Program'); goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); /** * Number of rows of operations displayed in each mode. * @type {Object.<string, number>} * @const */ turing.NUM_PROGRAM_TRACKS = { normalMode: 2, bonusMode: 3 }; /** * Number of operations per track in each mode. Some may be blank. * @type {Object.<string, number>} * @const */ turing.NUM_OPS_PER_TRACK = { normalMode: 8, bonusMode: 13 }; /** * Left offset of program tracks. * @type {number} * @const */ turing.TRACK_LEFT = 74; /** * Width of a bonus mode track. As wide as the doodle will allow. * @type {number} * @const */ turing.BONUS_TRACK_WIDTH = 500; /** * Center vertical offsets of the buttons for each track. * @type {Array.<number>} * @const * @private */ turing.TRACK_BUTTON_VERTICAL_MIDDLE_ = [150, 194]; /** * Center vertical offsets of the buttons for each track in bonus mode. * @type {Array.<number>} * @const * @private */ turing.BONUS_TRACK_BUTTON_VERTICAL_MIDDLE_ = [100, 140, 180]; /** * Delay in ms for an op button to push in when pressed. * This ought to be short because the user has already done something. * @type {number} * @const */ turing.OP_PUSH_IN_DELAY = 20; /** * Delay in ms for an op button to pop out when released. * @type {number} * @const */ turing.OP_POP_OUT_DELAY = 20; /** * Pixels of padding left of the first circle on the track. This is subtracted * from total track width so that circles are centered in the non-padding area. * @type {number} * @const */ turing.TRACK_LEFT_PAD = 31; /** * Pixels of padding right of the last circle on the track. This is subtracted * from total track width so that circles are centered in the non-padding area. * @type {number} * @const */ turing.TRACK_RIGHT_PAD = 9; /** * Pixels of padding top above the track in the track image. * @type {number} * @const */ turing.TRACK_TOP_PAD = 4; /** * The number of operations per program track in the current mode. * @type {number} * @private */ turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.normalMode; /** * The number of program tracks in the current mode. * @type {number} * @private */ turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.normalMode; /** * True if the game is done and we are running in bonus mode, else false if we * are in the normal mode. * @type {boolean} * @private */ turing.inBonusMode_ = false; /** * Sets up program display for bonus mode. */ turing.switchProgramsToBonusMode = function() { turing.inBonusMode_ = true; turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.bonusMode; turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.bonusMode; }; /** * Sets up program display for normal mode. */ turing.switchProgramsToNormalMode = function() { turing.inBonusMode_ = false; turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.normalMode; turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.normalMode; }; /** * The current op highlight color. * @type {string} * @private */ turing.opHighlightColor_ = 'y'; /** * Sets the op highlight color. * @param {string} color One of 'b', 'r', 'y', 'g' to set the hilight color. */ turing.setOpHighlightColor = function(color) { if (/^[bryg]$/.test(color)) { // The color is valid. turing.opHighlightColor_ = color; } else { // Invalid color. Shouldn't happen. Fall back to yellow. turing.opHighlightColor_ = 'y'; } }; /** * @return {boolean} True iff program display is in bonus mode. */ turing.isInBonusMode = function() { return turing.inBonusMode_; }; /** * A primitive step a program can do in one movement of the program counter. * @typedef {string} */ turing.Op; /** * Map from operation strings used in stored programs to sprite names. * @type {Object.<turing.Op, string>} * @const */ turing.OP_SPRITES = { 'L': 'o-left', 'R': 'o-right', '0': 'o-print0', '1': 'o-print1', 'D0': 'o-down0', 'D1': 'o-down1', 'D_': 'o-down_', 'B2': 'o-back2', 'B3': 'o-back3', 'B4': 'o-back4', 'RB2': 'o-rback2', 'RB3': 'o-rback3', 'RB4': 'o-rback4', 'U0': 'o-up0', 'U1': 'o-up1', 'U_': 'o-up_', '': 'o-blank', // These operations are in the same spirit as the ones above, but are only // used in bonus mode, and are not part of normal gameplay. '_': 'o-x', 'U': 'o-blank-up', 'D': 'o-blank-down', 'B8': 'o-back8', 'B9': 'o-back9' }; /** * A track is a row of program operations arranged from left to right in control * flow order. * @param {number} verticalPosition The vertical offset of the track center. * @param {boolean} loopTracksDown Iff true, the loop track points down, else * up. * @constructor */ turing.Track = function(verticalPosition, loopTracksDown) { /** * The vertical offset of the middle of this track. * @type {number} * @private */ this.verticalPosition_ = verticalPosition; /** * Iff true, loop branch tracks go down from the track, else up. * @type {boolean} * @private */ this.loopTracksDown_ = loopTracksDown; /** * This track's ops. * @type {Array.<turing.Op>} */ this.ops = []; /** * Holds the track and operation divs. * @type {Element} * @private */ this.container_; /** * Divs for each operation on this track. * @type {Array.<Element>} * @private */ this.opDivs_ = []; /** * A div showing the path of the first loop branch on this track. * @type {Element} * @private */ this.loopBranchDiv_; /** * Index of the operation which is a loop branch, or null if none. * @type {?number} * @private */ this.loopBranchIndex_ = null; /** * Mousedown handlers for operation circles. * @type {Array.<Function>} * @private */ this.opMouseDownHandlers_ = []; /** * Touchstart handlers for operation circles. * @type {Array.<Function>} * @private */ this.opTouchHandlers_ = []; /** * Mouseup handlers for operation circles. * @type {Array.<Function>} * @private */ this.opMouseUpHandlers_ = []; /** * Mouseout handlers for operation circles. * @type {Array.<Function>} * @private */ this.opMouseOutHandlers_ = []; /** * Whether each operation is pushed in. * @type {Array.<boolean>} * @private */ this.opPushedIn_ = []; /** * Iff true, operations on this track are currently hidden. * @type {boolean} * @private */ this.hidden_ = true; /** * If true, listen to clicks on operations, else ignore them. * @type {boolean} * @private */ this.interactive_ = false; }; /** * Creates DOM elements for the track and its operations. * - container: An overflow:hidden wrapper to hold everything. * -- trackDiv: A vertically centered horizontal line (i.e. the track) * -- ...ops: Individual ops, centered in equal-sized regions of track. */ turing.Track.prototype.create = function() { // Size container based on interactive state, which is larger. var opSize = turing.sprites.getSize('o-blank-i'); var trackSize = turing.sprites.getSize('track'); if (turing.inBonusMode_) { trackSize.width = turing.BONUS_TRACK_WIDTH; } this.container_ = turing.sprites.getEmptyDiv(); this.container_.style.width = trackSize.width + 'px'; this.container_.style.height = opSize.height + 'px'; this.container_.style.zIndex = 400; for (var i = 0; i < turing.numOpsPerTrack_; i++) { this.createOp_(i); } if (!turing.inBonusMode_) { var loopBranchTrackSize = turing.sprites.getSize('track-l4'); this.loopBranchDiv_ = turing.sprites.getDiv('track-l4'); this.loopBranchDiv_.style.display = 'none'; this.loopBranchDiv_.style.top = this.verticalPosition_ + 'px'; } this.container_.style.zIndex = 399; // Beneath buttons. this.container_.style.top = (this.verticalPosition_ - opSize.height / 2) + 'px'; this.container_.style.left = turing.inBonusMode_ ? '0' : turing.TRACK_LEFT + 'px'; }; /** * Creates a single operation div and binds a lot of event listeners on it. * @param {number} i The index of the operation to create. * @private */ turing.Track.prototype.createOp_ = function(i) { this.opDivs_[i] = turing.sprites.getDiv('o-dim-s'); var pos = this.getOpPosition('o-blank-s', i); this.opDivs_[i].style.left = pos.left + 'px'; this.opDivs_[i].style.top = pos.top + 'px'; if (!turing.inBonusMode_) { this.opMouseDownHandlers_[i] = goog.bind(this.pushInOp, this, i); this.opTouchHandlers_[i] = goog.bind(function() { this.opPushedIn_[i] = true; this.popOutOp(i, true); }, this); this.opMouseUpHandlers_[i] = goog.bind(this.popOutOp, this, i, true); this.opMouseOutHandlers_[i] = goog.bind(this.popOutOp, this, i, false); turing.util.listen(this.opDivs_[i], 'mousedown', this.opMouseDownHandlers_[i]); turing.util.listen(this.opDivs_[i], 'touchstart', this.opTouchHandlers_[i]); turing.util.listen(this.opDivs_[i], 'mouseup', this.opMouseUpHandlers_[i]); turing.util.listen(this.opDivs_[i], 'mouseout', this.opMouseOutHandlers_[i]); } this.opPushedIn_[i] = false; this.container_.appendChild(this.opDivs_[i]); }; /** * Computes the offset of an operation inside the track's container div. * @param {string} spriteName The sprite used for this operation. * @param {number} i The index of the operation. * @return {{top: number, left: number}} The position for this operation. */ turing.Track.prototype.getOpPosition = function(spriteName, i) { // Interactive operations are bigger than static operations. The track is // sized to hold the bigger ones, and we center the smaller ones in the same // footprint. var bigOpSize = turing.sprites.getSize('o-blank-i'); var trackSize = turing.sprites.getSize('track'); if (turing.inBonusMode_) { trackSize.width = turing.BONUS_TRACK_WIDTH; } // Center the bonus mode on the track (use the same padding as we do on the // right, plus a few px to look correct). var leftPadding = turing.inBonusMode_ ? turing.TRACK_RIGHT_PAD + 4 : turing.TRACK_LEFT_PAD; var trackWidthPerOp = (trackSize.width - turing.TRACK_RIGHT_PAD - leftPadding) / turing.numOpsPerTrack_; var opSize = turing.sprites.getSize(spriteName); var xOffs = Math.ceil((bigOpSize.width - opSize.width) / 2); var yOffs = Math.ceil((bigOpSize.height - opSize.height) / 2); return { left: (leftPadding + Math.floor(i * trackWidthPerOp + trackWidthPerOp / 2 - opSize.width / 2) - xOffs), top: yOffs }; }; /** * Sets a flag indicating whether operations on this track are currently hidden. * If hidden, op divs are not redrawn as program execution proceeds. * @param {boolean} hidden True iff op divs are hidden. */ turing.Track.prototype.setHidden = function(hidden) { this.hidden_ = hidden; }; /** * Sets whether the track is currently clickable. * No operations on the track should respond to clicks when a program is * running or when we are changing programs. * @param {boolean} interactive True iff track should be interactive. */ turing.Track.prototype.setInteractive = function(interactive) { this.interactive_ = interactive; this.redrawProgram(); }; /** * Gets the ith operation div in control flow order on a track. * @param {number} i Index into operations. * @return {Element} The operation div. */ turing.Track.prototype.getOpDiv = function(i) { return this.opDivs_[i]; }; /** * Gets the ith operation in control flow order on a track. * @param {number} i Index into operations. * @return {turing.Op} The operation. */ turing.Track.prototype.getOp = function(i) { return this.ops[i]; }; /** * Sets the value of the ith operation in control flow order on track. * @param {number} i Index into operations. * @param {turing.Op} value Desired value. */ turing.Track.prototype.setOp = function(i, value) { this.ops[i] = value; }; /** * Conditional branch operations from a higher track to a lower one. * @type {Array.<turing.Op>} * @private * @const */ turing.COND_BRANCH_DOWN_OPS_ = ['D0', 'D1', 'D_']; /** * Conditional branch operations from a lower track to a higher one. * @type {Array.<turing.Op>} * @private * @const */ turing.COND_BRANCH_UP_OPS_ = ['U0', 'U1', 'U_']; /** * Loop branch operations. * @type {Array.<turing.Op>} * @private * @const */ turing.LOOP_BRANCH_OPS_ = ['B2', 'B3', 'B4']; /** * Printing operations. * @type {Array.<turing.Op>} * @private * @const */ turing.PRINT_OPS_ = ['0', '1']; /** * Tape movement operations. * @type {Array.<turing.Op>} * @private * @const */ turing.MOVE_OPS_ = ['L', 'R']; /** * Cycle to next valid op in this op's group. * @param {number} i Index of relevant op. */ turing.Track.prototype.cycleOp = function(i) { if (!this.interactive_) { return; } var op = this.getOp(i); if (!op || op.charAt(0) != '*') { // This operation is not clickable. return; } op = op.substr(1); this.setOp(i, '*' + ( turing.util.getNextValue(turing.COND_BRANCH_UP_OPS_, op) || turing.util.getNextValue(turing.COND_BRANCH_DOWN_OPS_, op) || turing.util.getNextValue(turing.LOOP_BRANCH_OPS_, op) || turing.util.getNextValue(turing.PRINT_OPS_, op) || turing.util.getNextValue(turing.MOVE_OPS_, op) || op)); }; /** * Push in an op button. * @param {number} i Index of the relevant op. * @param {Event} event mousedown or touchstart event. */ turing.Track.prototype.pushInOp = function(i, event) { var spec = this.getOp(i); if (!this.interactive_ || !spec || spec.charAt(0) != '*' || this.opPushedIn_[i]) { // The button might still be pushed in if the pop-out animation from a // previous click is still playing. return; } this.opPushedIn_[i] = true; var baseName = turing.Track.prototype.getOpSpriteBaseName_(spec); turing.anim.animateFromSprites(this.opDivs_[i], [baseName + '-i-out', baseName + '-i', baseName + '-i-in'], turing.OP_PUSH_IN_DELAY); }; /** * Pop out an op button. * @param {number} i Index of the relevant op. * @param {boolean} shouldChange True iff we should cycle the op button. * @param {Event} event mouseup or mouseout event. */ turing.Track.prototype.popOutOp = function(i, shouldChange, event) { var spec = this.getOp(i); if (!this.interactive_ || !spec || spec.charAt(0) != '*' || !this.opPushedIn_[i]) { return; } if (shouldChange) { this.cycleOp(i); } spec = this.getOp(i); var baseName = turing.Track.prototype.getOpSpriteBaseName_(spec); turing.anim.animateFromSprites(this.opDivs_[i], [baseName + '-i-in', baseName + '-i', baseName + '-i-out'], turing.OP_POP_OUT_DELAY, goog.bind(function(i) { this.opPushedIn_[i] = false; this.redrawOp(i, false); }, this, i)); }; /** * Gets the base name of the sprite for the given operation. * @param {string} spec An operation spec like D_. * @return {string} The name of the sprite with no suffixes. * @private */ turing.Track.prototype.getOpSpriteBaseName_ = function(spec) { if (spec && spec.charAt(0) == '*') { spec = spec.substr(1); } if (this.loopTracksDown_ && (spec == 'B2' || spec == 'B3' || spec == 'B4')) { // Appending R reverses the direction of the loop so that it looks like it's // pointing down to the lower track loop. spec = 'R' + spec; } return turing.OP_SPRITES[spec || '']; }; /** * Sets the track's abstract operations, without updating or showing it. * Makes a copy of the given array so that it can be changed without changing * a constant program definition. * @param {Array.<turing.Op>} ops Program operations. */ turing.Track.prototype.setOps = function(ops) { this.ops = ops.slice(0); // Copy ops. this.loopBranchIndex_ = null; for (var i = 0; i < this.ops.length; i++) { if (this.ops[i] && this.ops[i].match(/B/)) { // /B/ matches operation codes containing B. Loop branches are the only // such operations so this is a loop branch. this.loopBranchIndex_ = i; break; } } }; /** * Changes the operations on a track (and animates it into its new state). * @param {Array.<turing.Op>} ops A list of new operations. */ turing.Track.prototype.change = function(ops) { this.setOps(ops); this.redrawProgram(); }; /** * Redraws the current program. */ turing.Track.prototype.redrawProgram = function() { if (!turing.inBonusMode_ && this.loopBranchIndex_ == null) { // If there is no loop branch, hide backwards pointing track. // (If there is a loop branch, it'll be shown from redrawOp below.) this.loopBranchDiv_.style.display = 'none'; } for (var i = 0; i < turing.numOpsPerTrack_; i++) { this.redrawOp(i, false); } }; /** * Updates the sprite for an operation. * @param {number} i The index of the operation on the track. * @param {boolean} lit Whether the operation is currently active. */ turing.Track.prototype.redrawOp = function(i, lit) { if (this.hidden_) { return; } var opDiv = this.getOpDiv(i); var spec = this.getOp(i) || ''; var suffix = ''; if (spec && spec.charAt(0) == '*') { // * means the operation is clickable. if (this.interactive_) { if (this.opPushedIn_[i]) { suffix = '-i-in'; } else { suffix = '-i-out'; } opDiv.style.cursor = 'pointer'; } else { // The operation is clickable, but not right now. It should be flat. suffix = lit ? '-i-lit' : '-i'; opDiv.style.cursor = 'default'; } } else { // The operation is never clickable. suffix = lit ? '-s-lit-' + turing.opHighlightColor_ : '-s'; opDiv.style.cursor = 'default'; } var spriteName = this.getOpSpriteBaseName_(spec); var size = turing.sprites.getSize(spriteName + suffix); opDiv.style.background = turing.sprites.getBackground( spriteName + suffix); // Interactive buttons are bigger than static buttons, so we may need to // recenter the button. var pos = this.getOpPosition(spriteName + suffix, i); opDiv.style.left = pos.left + 'px'; opDiv.style.top = pos.top + 'px'; opDiv.style.width = size.width + 'px'; opDiv.style.height = size.height + 'px'; if (i == this.loopBranchIndex_) { this.redrawLoopBranchTrack_(spriteName + suffix); } }; /** * Redraws the segment showing the path for a loop branch on this track. * @param {string} opSpriteName The sprite name for the loop branch operation * where the segment begins. * @private */ turing.Track.prototype.redrawLoopBranchTrack_ = function(opSpriteName) { if (this.loopBranchIndex_ == null || turing.inBonusMode_) { return; } var spec = this.getOp(this.loopBranchIndex_); // /(\d)$/ extracts the last single digit in the operation code, which for // branches is the number of states to branch back (i.e. the distance). var branchDist = spec.match(/(\d)$/); var opSize = turing.sprites.getSize(opSpriteName); var pos = this.getOpPosition(opSpriteName, this.loopBranchIndex_); var loopBranchSprite = 'track-' + (this.loopTracksDown_ ? 'l' : 'u') + branchDist[1]; var loopBranchSize = turing.sprites.getSize(loopBranchSprite); this.loopBranchDiv_.style.background = turing.sprites.getBackground( loopBranchSprite); this.loopBranchDiv_.style.left = Math.floor(turing.TRACK_LEFT + pos.left - loopBranchSize.width + opSize.width / 2 + 4) + 'px'; var middleOfButtons = this.verticalPosition_; // For the top loop, its bottom should be aligned with the middle of the // buttons. var yOffs = this.loopTracksDown_ ? -3 : (-loopBranchSize.height + 2); this.loopBranchDiv_.style.top = Math.floor(middleOfButtons + yOffs) + 'px'; this.loopBranchDiv_.style.width = loopBranchSize.width + 'px'; this.loopBranchDiv_.style.height = loopBranchSize.height + 'px'; this.loopBranchDiv_.style.display = 'block'; }; /** * Since we're a touch device, destroy mouse handlers. */ turing.Track.prototype.setTouchDevice = function() { this.destroyEventHandlers_(true); }; /** * Destroy the event handlers. Optionally save the touch events. This allows * us to kill the mouse handlers if we're on a touch device. Note that we * lazily check if we're a touch device by waiting for a touchstart event in * turing.js rather than doing useragent parsing. * @param {boolean=} opt_saveTouch Whether to preserve touch event handlers. * @private */ turing.Track.prototype.destroyEventHandlers_ = function(opt_saveTouch) { for (var i = 0; i < this.opMouseDownHandlers_.length; i++) { turing.util.unlisten(this.opDivs_[i], 'mousedown', this.opMouseDownHandlers_[i]); } this.opMouseDownHandlers_.splice(0); if (!opt_saveTouch) { for (var i = 0; i < this.opTouchHandlers_.length; i++) { turing.util.unlisten(this.opDivs_[i], 'touchstart', this.opTouchHandlers_[i]); } this.opTouchHandlers_.splice(0); } for (var i = 0; i < this.opMouseUpHandlers_.length; i++) { turing.util.unlisten(this.opDivs_[i], 'mouseup', this.opMouseUpHandlers_[i]); } this.opMouseUpHandlers_.splice(0); for (var i = 0; i < this.opMouseOutHandlers_.length; i++) { turing.util.unlisten(this.opDivs_[i], 'mouseout', this.opMouseOutHandlers_[i]); } this.opMouseOutHandlers_.splice(0); }; /** * Cleans up dom elements and removes event listeners. */ turing.Track.prototype.destroy = function() { this.destroyEventHandlers_(); for (var i = 0; i < this.opDivs_.length; i++) { turing.util.removeNode(this.opDivs_[i]); } this.opDivs_.splice(0); turing.util.removeNode(this.container_); this.container_ = null; turing.util.removeNode(this.loopBranchDiv_); this.loopBranchDiv_ = null; }; /** * Adds to dom. * @param {Element} elem dom parent. */ turing.Track.prototype.attachTo = function(elem) { elem.appendChild(this.container_); if (this.loopBranchDiv_) { // Not shown in bonus mode. elem.appendChild(this.loopBranchDiv_); } }; /** * A Turing machine program shown as a set of tracks. * @constructor */ turing.Program = function() { /** * Tracks containing operations. * @type {Array.<turing.Track>} * @private */ this.tracks_ = []; for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i] = new turing.Track(turing.inBonusMode_ ? turing.BONUS_TRACK_BUTTON_VERTICAL_MIDDLE_[i] : turing.TRACK_BUTTON_VERTICAL_MIDDLE_[i], i == 1); } /** * The div containing the track image. * @type {Element} * @private */ this.trackDiv_; /** * Pieces of track joining the top track to the bottom track. * @type {Array.<Element>} * @private */ this.trackDescenders_ = []; /** * How many tracks does the current program have? * @type {number} * @private */ this.numActiveTracks_ = 0; /** * The current hilit operation's track number. * @type {number} * @private */ this.curTrack_ = 0; /** * The current hilit operation's position on its track. * @type {number} * @private */ this.curTrackPos_ = 0; /** * The next operation's track number. * @type {number} * @private */ this.nextTrack_ = 0; /** * The next operation's position on its track. * @type {number} * @private */ this.nextTrackPos_ = 0; /** * True iff the program should end on the next operation. * @type {boolean} * @private */ this.nextPosIsEnd_ = true; /** * Are the program's operations hidden? * @type {boolean} * @private */ this.hidden_ = true; /** * Can the user click on clickable operations right now? * @type {boolean} * @private */ this.interactive_ = false; }; /** * Creates dom elements for the program display. */ turing.Program.prototype.create = function() { for (var i = 0; i < this.tracks_.length; i++) { this.tracks_[i].create(); } if (!turing.inBonusMode_) { var opSize = turing.sprites.getSize('o-blank-i'); var middleOfTopTrack = turing.TRACK_BUTTON_VERTICAL_MIDDLE_[0]; this.trackDiv_ = turing.sprites.getDiv('track'); this.trackDiv_.style.left = turing.TRACK_LEFT + 'px'; this.trackDiv_.style.top = middleOfTopTrack - turing.TRACK_TOP_PAD + 'px'; // Bonus mode has no lines between tracks (they don't really fit). var trackDownSize = turing.sprites.getSize('track-vert'); var trackSize = turing.sprites.getSize('track'); var trackWidthPerOp = (trackSize.width - turing.TRACK_LEFT_PAD - turing.TRACK_RIGHT_PAD) / turing.numOpsPerTrack_; for (var i = 0; i < turing.numOpsPerTrack_; i++) { this.trackDescenders_[i] = turing.sprites.getDiv('track-vert'); // Vertical lines between operations on a pair of tracks are centered // beneath those operations. this.trackDescenders_[i].style.left = Math.floor(turing.TRACK_LEFT_PAD + turing.TRACK_LEFT + i * trackWidthPerOp + trackWidthPerOp / 2 - trackDownSize.width / 2 - 1) + 'px'; this.trackDescenders_[i].style.top = middleOfTopTrack + 'px'; this.trackDescenders_[i].style.zIndex = 398; // Behind operations. this.trackDescenders_[i].style.display = 'none'; } } }; /** * Cleans up dom elements and event listeners. */ turing.Program.prototype.destroy = function() { for (var i = 0; i < this.tracks_.length; i++) { this.tracks_[i].destroy(); } turing.util.removeNode(this.trackDiv_); for (var i = 0; i < this.trackDescenders_.length; i++) { turing.util.removeNode(this.trackDescenders_[i]); } this.trackDescenders_.splice(0); }; /** * Attaches dom nodes beneath elem. * @param {Element} elem Parent. */ turing.Program.prototype.attachTo = function(elem) { for (var i = 0; i < this.tracks_.length; i++) { this.tracks_[i].attachTo(elem); } if (!turing.inBonusMode_) { // Bonus mode doesn't have track lines. elem.appendChild(this.trackDiv_); for (var i = 0; i < this.trackDescenders_.length; i++) { elem.appendChild(this.trackDescenders_[i]); } } }; /** * Dims any lit operations. */ turing.Program.prototype.reset = function() { for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i].redrawProgram(); } if (!turing.inBonusMode_) { this.redrawDescenders_(); } }; /** * Draws lines connecting the tracks wherever there are up or down operations. * @private */ turing.Program.prototype.redrawDescenders_ = function() { for (var i = 0; i < turing.numOpsPerTrack_; i++) { this.trackDescenders_[i].style.background = turing.sprites.getBackground('track-vert'); var hasBranch = false; for (var j = 0; j < turing.numTracks_; j++) { var spec = this.tracks_[j].getOp(i); if (!this.hidden_ && spec && spec.match(/D|U/)) { // /D|U/ matches any conditional down-if or up-if branches (those are // the only operations which contain 'D' or 'U'). hasBranch = true; } } this.trackDescenders_[i].style.display = hasBranch ? 'block' : 'none'; } }; /** * Changes to a new program. * @param {Array.<Array.<turing.Op>>} trackOps The operations for each * valid program track. Note: This code supports 1 or 2 track programs. * @param {boolean=} opt_hidden Iff true, change the program contents, but * keep tracks hidden. */ turing.Program.prototype.change = function(trackOps, opt_hidden) { this.curTrack_ = 0; this.curTrackPos_ = 0; this.nextTrack_ = 0; this.nextTrackPos_ = 0; this.nextPosIsEnd_ = false; this.hidden_ = opt_hidden || false; this.numActiveTracks_ = trackOps.length; for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i].setOps(trackOps[i] || []); this.tracks_[i].setHidden(opt_hidden || false); } this.reset(); }; /** * Sets whether program tracks are currently accepting clicks. * @param {boolean} interactive True iff tracks should accept clicks. */ turing.Program.prototype.setInteractive = function(interactive) { this.interactive_ = interactive; for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i].setInteractive(interactive); } }; /** * Gets the current track number. * @return {number} Current instruction's track. */ turing.Program.prototype.getCurTrack = function() { return this.curTrack_; }; /** * Gets the current position on the current track. * @return {number} Current instruction's op index within track. */ turing.Program.prototype.getCurTrackPos = function() { return this.curTrackPos_; }; /** * @return {boolean} True iff next position is past end of program. */ turing.Program.prototype.isNextPosEnd = function() { return this.nextPosIsEnd_; }; /** * Sets the track and position for the next operation to be run. Stays put if * the new position is not a valid program position. * @param {number} track The new track. * @param {number} pos The new position. */ turing.Program.prototype.setNextPos = function(track, pos) { if (track >= 0 && track < this.numActiveTracks_ && pos >= 0 && pos < turing.numOpsPerTrack_) { this.nextTrack_ = track; this.nextTrackPos_ = pos; this.nextPosIsEnd_ = false; } else { this.nextPosIsEnd_ = true; } }; /** * Sets the current position to the next position and redraws highlights. */ turing.Program.prototype.goToNextPos = function() { this.dimCurOp(); if (!this.nextPosIsEnd_) { this.curTrack_ = this.nextTrack_; this.curTrackPos_ = this.nextTrackPos_; this.lightCurOp_(); } }; /** * Dims the current active program operation. */ turing.Program.prototype.dimCurOp = function() { this.tracks_[this.curTrack_].redrawOp(this.curTrackPos_, false); }; /** * Highlights the current active program operation. * @private */ turing.Program.prototype.lightCurOp_ = function() { this.tracks_[this.curTrack_].redrawOp(this.curTrackPos_, true); }; /** * Gets the current program operation to execute. * @return {turing.Op} The current operation. */ turing.Program.prototype.getCurOp = function() { return this.tracks_[this.curTrack_].getOp(this.curTrackPos_); }; /** * Notify the tracks that we're on a tablet. */ turing.Program.prototype.setTouchDevice = function() { for (var i = 0; i < turing.numTracks_; i++) { this.tracks_[i].setTouchDevice(); } };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Shows the Google logo. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.Logo'); goog.require('turing.anim'); goog.require('turing.sprites'); goog.require('turing.util'); /** * The names of letters in the logo, in order, corresponding to sprites. * @type {Array.<string>} * @const */ turing.LOGO_LETTERS = ['G', 'o1', 'o2', 'g', 'l', 'e']; /** * The left offset of the logo container. * @type {string} * @const */ turing.LOGO_LEFT = '79px'; /** * The top offset of the logo container. * @type {string} * @const */ turing.LOGO_TOP = '24px'; /** * The tops of each letter so that they line up correctly vertically. * @type {Array.<string>} * @const * @private */ turing.LETTER_TOPS_ = ['1px', '11px', '11px', '11px', '0', '11px']; /** * The lefts of each letter so that they line up correctly. * @type {Array.<string>} * @const * @private */ turing.LETTER_LEFTS_ = ['0', '33px', '57px', '79px', '100px', '111px']; /** * The number of animation frames used to light up the logo letters. * @type {number} * @const * @private */ turing.NUM_LETTER_ANIMATION_FRAMES_ = 8; /** * A Google logo where each letter can light up or dim individually. * @constructor */ turing.Logo = function() { /** * Divs for each letter. * @type {Array.<Element>} * @private */ this.letters_ = []; /** * Container div holding all letters. * @type {Element} * @private */ this.container_; }; /** * Attaches the logo under a dom element. * @param {Element} elem Parent element. */ turing.Logo.prototype.attachTo = function(elem) { elem.appendChild(this.container_); }; /** * Creates the dom elements for the logo letters. * @param {number} numLettersOn How many letters are initially on. */ turing.Logo.prototype.create = function(numLettersOn) { this.container_ = turing.sprites.getEmptyDiv(); this.container_.style.left = turing.LOGO_LEFT; this.container_.style.top = turing.LOGO_TOP; for (var i = 0, letter; letter = turing.LOGO_LETTERS[i]; i++) { var spriteName = i < numLettersOn ? letter + (turing.NUM_LETTER_ANIMATION_FRAMES_ - 1) : letter + '0'; this.letters_[i] = turing.sprites.getDiv(spriteName); this.letters_[i].style.left = turing.LETTER_LEFTS_[i]; this.letters_[i].style.top = turing.LETTER_TOPS_[i]; this.container_.appendChild(this.letters_[i]); var letterSize = turing.sprites.getSize(spriteName); } }; /** * Destroys the dom elements for logo letters. */ turing.Logo.prototype.destroy = function() { turing.util.removeNode(this.container_); this.container_ = null; for (var i = 0, letter; letter = this.letters_[i++]; ) { turing.util.removeNode(letter); } this.letters_.splice(0); }; /** * Return an array of backgrounds we can use to animate the hightlighting or * dimming of the given letter. * @param {string} letter The letter to animate. * @param {boolean} startDim If true, we dim the letter instead of highlighting. * @return {Array.<string>} The backgrounds which can be used to animate it. * @private */ turing.Logo.prototype.getAnimationBackgrounds_ = function(letter, startDim) { var backgrounds = []; for (var i = 0; i < turing.NUM_LETTER_ANIMATION_FRAMES_; i++) { backgrounds[i] = turing.sprites.getBackground( letter + (startDim ? i : turing.NUM_LETTER_ANIMATION_FRAMES_ - 1 - i)); } return backgrounds; }; /** * Lights up the letter at the given position. * @param {number} pos The index of the letter to light up. * @param {number=} opt_duration The duration to animate lighting the logo * letter. */ turing.Logo.prototype.lightLetterAtPosition = function(pos, opt_duration) { if (!this.letters_[pos]) { return; } var letter = turing.LOGO_LETTERS[pos]; if (!opt_duration) { this.letters_[pos].style.background = turing.sprites.getBackground( letter + (turing.NUM_LETTER_ANIMATION_FRAMES_ - 1)); } else { turing.anim.animateThroughBackgrounds(this.letters_[pos], this.getAnimationBackgrounds_(letter, true), opt_duration); } }; /** * Dims the letter at the given position. * @param {number} pos The index of the letter to dim. * @param {number=} opt_duration The duration to animate dimming the logo * letter. */ turing.Logo.prototype.dimLetterAtPosition = function(pos, opt_duration) { var letterDiv = this.letters_[pos]; if (!letterDiv) { return; } var letter = turing.LOGO_LETTERS[pos]; if (!opt_duration) { letterDiv.style.background = turing.sprites.getBackground(letter + '0'); } else { turing.anim.animateThroughBackgrounds(letterDiv, this.getAnimationBackgrounds_(letter, false), opt_duration); } }; /** * Dims all letters. * @param {number=} opt_duration The duration to animate dimming the logo * letters. */ turing.Logo.prototype.dim = function(opt_duration) { for (var i = 0; i < this.letters_.length; i++) { turing.anim.delay( goog.bind(this.dimLetterAtPosition, this, i, opt_duration), 250); } }; /** * Successively dim each letter of the logo from the last to the first. * @param {function()=} opt_doneCallback Called when the logo is dim again. */ turing.Logo.prototype.deluminate = function(opt_doneCallback) { var numLetters = turing.LOGO_LETTERS.length; for (var i = 0; i < numLetters; i++) { turing.anim.delay( goog.bind(this.dimLetterAtPosition, this, numLetters - (i + 1), 500), 250 * i); } turing.anim.delay( goog.bind(function() { this.dim(); opt_doneCallback(); }, this), 250 * (1 + turing.LOGO_LETTERS.length) + 500); };
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Helpers for loading sprites. * @author jered@google.com (Jered Wierzbicki) */ goog.provide('turing.sprites'); goog.require('turing.deferredsprites.offsets'); goog.require('turing.sprites.offsets'); /** * Path to the main sprite. * @type {string} * @const */ turing.sprites.PATH = 'images/sprite.png'; /** * Path to the deferred sprite. * @type {string} * @const */ turing.sprites.DEFERRED_SPRITE_PATH = 'images/deferred_sprite.png'; /** * Gets the width and height of the named sprite. * @param {string} name A sprite name. * @return {{width: number, height: number}} */ turing.sprites.getSize = function(name) { var rect = turing.sprites.offsets.RECTS[name] || turing.deferredsprites.offsets.RECTS[name]; return {width: rect.width, height: rect.height}; }; /** * Gets a string with background: CSS to select a sprite. * @param {string} name The name of the desired sprite. * @return {string} background: CSS. */ turing.sprites.getBackground = function(name) { var rect = turing.sprites.offsets.RECTS[name] || turing.deferredsprites.offsets.RECTS[name]; if (!rect) { // For debugging purposes, make it easy to see the missing sprite. return 'red'; } var deferred = !turing.sprites.offsets.RECTS[name] && turing.deferredsprites.offsets.RECTS[name]; var path = deferred ? turing.sprites.DEFERRED_SPRITE_PATH : turing.sprites.PATH; return 'url(' + path + ') ' + -rect.x + 'px ' + -rect.y + 'px no-repeat'; }; /** * Gets a div containing the requested sprite. * @param {string} name The name of the desired sprite. * @return {Element} The sprite div. */ turing.sprites.getDiv = function(name) { var div = turing.sprites.getEmptyDiv(); var rect = turing.sprites.offsets.RECTS[name]; // In practice, we should always have a sprite offset for a given name so we // shouldn't be using these fallback values, but if we don't we render a // 50x50 square and getBackground will return 'red' so that we can quickly // and easily see the missing sprite. div.style.width = rect ? (rect.width + 'px') : '50px'; div.style.height = rect ? (rect.height + 'px') : '50px'; div.style.background = turing.sprites.getBackground(name); div.style['webkitTapHighlightColor'] = 'rgba(0,0,0,0)'; return div; }; /** * Gets an empty, unselectable div. * @return {Element} The div. */ turing.sprites.getEmptyDiv = function() { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.userSelect = 'none'; div.style.webkitUserSelect = 'none'; div.style['webkitTapHighlightColor'] = 'rgba(0,0,0,0)'; div.style.MozUserSelect = 'none'; div.unselectable = 'on'; return div; }; /** * Preloads sprites. * @param {string} path The path to the image to preload. * @return {Element} the image element used to preload the sprite. */ turing.sprites.preload = function(path) { var img = document.createElement('img'); img.src = path; return img; };
JavaScript
$().ready(function () { $("#DepartStartDate,#DepartEndDate").datepicker({ dateFormat: 'yy年mm月dd日', numberOfMonths: 3, beforeShow: DepartDateRange }); $("#LeaveStartDate,#LeaveEndDate").datepicker({ dateFormat: 'yy年mm月dd日', numberOfMonths: 3, beforeShow: LeaveDateRange }); $("#HotelCheckinDate,#HotelCheckoutDate").datepicker({ dateFormat: 'yy年mm月dd日', numberOfMonths: 3, beforeShow: HotelCheckDateRange }); function DepartDateRange(input) { return { minDate: (input.id == "DepartEndDate" ? $("#DepartStartDate").datepicker("getDate") : null), maxDate: (input.id == "DepartStartDate" ? $("#DepartEndDate").datepicker("getDate") : null) }; } function LeaveDateRange(input) { return { minDate: (input.id == "LeaveEndDate" ? $("#LeaveStartDate").datepicker("getDate") : null), maxDate: (input.id == "LeaveStartDate" ? $("#LeaveEndDate").datepicker("getDate") : null) }; } function HotelCheckDateRange(input) { return { minDate: (input.id == "HotelCheckoutDate" ? $("#HotelCheckinDate").datepicker("getDate") : null), maxDate: (input.id == "HotelCheckinDate" ? $("#HotelCheckoutDate").datepicker("getDate") : null) }; } $(".reviewedrole input").change(function () { if ($(this).attr("id") == "ReviewedRole_1") $("#admin-confirm").slideDown(); else { $("#admin-confirm").slideUp(); } }); $("form").submit(function () { if ($(this).valid()) { $(".btn-container input").css("disable", "disable"); $(".btn-container input").val("保存中……"); } }); });
JavaScript
/* [===========================================================================] [ Copyright (c) 2009, Helori LAMBERTY ] [ All rights reserved. ] [ ] [ Redistribution and use in source and binary forms, with or without ] [ modification, are permitted provided that the following conditions ] [ are met: ] [ ] [ * Redistributions of source code must retain the above copyright ] [ notice, this list of conditions and the following disclaimer. ] [ ] [ * Redistributions in binary form must reproduce the above copyright ] [ notice, this list of conditions and the following disclaimer in ] [ the documentation and/or other materials provided with the ] [ distribution. ] [ ] [ * Neither the name of NotesFor.net nor the names of its ] [ contributors may be used to endorse or promote products derived ] [ from this software without specific prior written permission. ] [ ] [ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ] [ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ] [ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ] [ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ] [ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ] [ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ] [ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ] [ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ] [ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ] [ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE ] [ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ] [ DAMAGE. ] [===========================================================================] */ (function($) { $.fn.lightBox = function(settings) { /// <summary> /// Init the JQuery ligntbox settings. /// </summary> /// <param name="settings" type="Options"> /// 1: overlayBgColor - (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color. /// 2: overlayOpacity - (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9. /// 3: fixedNavigation - (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface. /// 4: imageLoading - (string) Path and the name of the loading icon image /// 5: imageBtnPrev - (string) Path and the name of the prev button image /// 6: imageBtnNext - (string) Path and the name of the next button image /// 7: imageBtnClose - (string) Path and the name of the close button image /// 8: imageBlank - (string) Path and the name of a blank image (one pixel) /// 9: imageBtnBottomPrev - (string) Path and the name of the bottom prev button image /// 10: imageBtnBottomNext - (string) (string) Path and the name of the bottom next button image /// 11: imageBtnPlay - (string) Path and the name of the close button image /// 12: imageBtnStop - (string) Path and the name of the play button image /// 13: containerBorderSize - (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value /// 14: containerResizeSpeed - (integer) Specify the resize duration of container image. These number are miliseconds. 500 is default. /// 15: txtImage - (string) Specify text "Image" /// 16: txtOf - (string) Specify text "of" /// 17: txtPrev - (string) Specify text "previous" /// 18: keyToNext - (string) Specify text "next" /// 19: keyToClose - (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to. /// 20: keyToPrev - (string) (p = previous) Letter to show the previous image. /// 21: keyToNext - (string) (n = next) Letter to show the next image. /// 22: slideShowTimer - (integer) number of milliseconds to change image by default 5000. /// </param> /// <returns type="jQuery" /> settings = jQuery.extend({ // Configuration related to overlay overlayBgColor: '#000', overlayOpacity: 0.8, // Configuration related to navigation fixedNavigation: false, // Configuration related to images imageLoading: '/scripts/NFLightBox/images/loading.gif', imageBtnPrev: '/scripts/NFLightBox/images/prev.png', imageBtnNext: '/scripts/NFLightBox/images/next.png', imageBtnClose: '/scripts/NFLightBox/images/close.png', imageBlank: '/scripts/NFLightBox/images/lightbox-blank.gif', imageBtnBottomPrev: '/scripts/NFLightBox/images/btm_prev.gif', imageBtnBottomNext: '/scripts/NFLightBox/images/btm_next.gif', imageBtnPlay: '/scripts/NFLightBox/images/start.png', imageBtnStop: '/scripts/NFLightBox/images/pause.png', // Configuration related to container image box containerBorderSize: 10, containerResizeSpeed: 500, // Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts. txtImage: 'Image', txtOf: 'of', txtPrev: '&nbsp;Previous', txtNext: '&nbsp;Next', // Configuration related to keyboard navigation keyToClose: 'c', keyToPrev: 'p', keyToNext: 'n', //Configuration related to slide show slideShowTimer: 5000, // Don´t alter these variables in any way step: 0, imageArray: [], slideShow: 'start', activeImage: 0 }, settings); // Caching the jQuery object with all elements matched var jQueryMatchedObj = this; // This, in this context, refer to jQuery object function _initialize() { _start(this, jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked return false; // Avoid the browser following the link } function _start(objClicked, jQueryMatchedObj) { /// <summary> /// Start the jQuery lightBox plugin. /// </summary> /// <param name="objClicked" type="object">objClicked The object (link) whick the user have clicked</param> /// <param name="jQueryMatchedObj" type="object">jQueryMatchedObj The jQuery object with all elements matched</param> // Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay. $('embed, object, select').css({ 'visibility': 'hidden' }); // Call the function to create the markup structure; style some elements; assign events in some elements. _set_interface(); // Unset total images in imageArray settings.imageArray.length = 0; // Unset image active information settings.activeImage = 0; // We have an image set? Or just an image? Let´s see it. if (jQueryMatchedObj.length == 1) { settings.imageArray.push(new Array(objClicked.getAttribute('href'), objClicked.getAttribute('title'))); } else { // Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references for (var i = 0; i < jQueryMatchedObj.length; i++) { settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'), jQueryMatchedObj[i].getAttribute('title'))); } } while (settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href')) { settings.activeImage++; } // Call the function that prepares image exibition _set_image_to_view(); } function _set_interface() { // Apply the HTML markup into body tag //$('body').append('<div id="jquery-overlay" /><div id="jquery-box"><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image-box-top"><div id="lightbox-container-image-box-top-left"><img src="' + settings.imageBtnPlay + '"></div><div id="lightbox-container-image-box-top-middle"></div><div id="lightbox-container-image-box-top-right"><img src="' + settings.imageBtnClose + '"></div></div><div id="lightbox-container-image"><img id="lightbox-image"/></div><div id="lightbox-nav" style="display: block;"><a id="lightbox-nav-btnPrev" href="#" /><a id="lightbox-nav-btnNext" href="#" /></div><div id="lightbox-loading" style="display: none;"><a id="lightbox-loading-link" href="#"><img src="' + settings.imageLoading + '"></a></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><span id="lightbox-image-details-caption">Image name</span> <span id="lightbox-image-details-currentNumber"></span>&nbsp;|&nbsp;<div id="lightbox-image-details-previous-image"><img src="' + settings.imageBtnBottomPrev + '"><span id="lightbox-image-details-previous-text">' + settings.txtPrev + '</span>&nbsp;</div><div id="lightbox-image-details-next-image"><img src="' + settings.imageBtnBottomNext + '"><span id="lightbox-image-details-next-text">' + settings.txtNext + '</span></div></div></div></div>'); $('body').append('<div id="jquery-overlay" /><div id="jquery-box"><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image-box-top"><div id="lightbox-container-image-box-top-left"><img src="' + settings.imageBtnPlay + '"></div><div id="lightbox-container-image-box-top-middle"></div><div id="lightbox-container-image-box-top-right"><img src="' + settings.imageBtnClose + '"></div></div><div id="lightbox-container-image"><img id="lightbox-image"/></div><div id="lightbox-nav" style="display: block;"><a id="lightbox-nav-btnPrev" href="#" title="' + settings.txtPrev + '" /><a id="lightbox-nav-btnNext" href="#" title="' + settings.txtNext + '" /></div><div id="lightbox-loading" style="display: none;"><a id="lightbox-loading-link" href="#"><img src="' + settings.imageLoading + '"></a></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><span id="lightbox-image-details-caption">Image name</span> <span id="lightbox-image-details-currentNumber"></span>&nbsp;|&nbsp;<div id="lightbox-image-details-previous-image"><img src="' + settings.imageBtnBottomPrev + '" alt="' + settings.txtPrev + '">&nbsp;</div><div id="lightbox-image-details-next-image"><img src="' + settings.imageBtnBottomNext + '" alt="' + settings.txtNext + '"></div></div></div></div>'); $('#lightbox-container-image-box').corner(); $('#lightbox-container-image-data-box').corner(); // Get page sizes var arrPageSizes = ___getPageSize(); // Style overlay and show it $('#jquery-overlay').css({ backgroundColor: settings.overlayBgColor, opacity: settings.overlayOpacity, width: arrPageSizes[0], height: arrPageSizes[1] }).fadeIn(); // Get page scroll var arrPageScroll = ___getPageScroll(); // Calculate top and left offset for the jquery-lightbox div object and show it $('#jquery-lightbox').css({ top: arrPageScroll[1] + (arrPageSizes[3] / 10), left: arrPageScroll[0] }).show(); // Assigning click events in elements to close overlay // $('#jquery-overlay,#jquery-lightbox').click(function() { // _finish(); // }); // Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects $('#lightbox-container-image-box-top-right img').click(function() { _finish(); return false; }); //Start/Stop the slide show $('#lightbox-container-image-box-top-left img').click(function() { if (settings.slideShow == 'start') { $('#lightbox-container-image-box-top-left img')[0].src = settings.imageBtnStop; settings.step = 0; $('#lightbox-container-image-box-top-left img').everyTime(settings.slideShowTimer / Math.round(settings.slideShowTimer / 125), "timer", function(i) { _set_timer(); }, Math.round(settings.slideShowTimer / 125)); settings.slideShow = 'stop'; } else { $('#lightbox-container-image-box-top-left img')[0].src = settings.imageBtnPlay; $('#lightbox-container-image-box-top-left img').stopTime("timer"); settings.step = 0; $("#lightbox-container-image-box-top-middle").reportprogress(settings.step, Math.round(settings.slideShowTimer / 125)); settings.slideShow = 'start'; } return false; }); // If window was resized, calculate the new overlay dimensions $(window).resize(function() { // Get page sizes var arrPageSizes = ___getPageSize(); // Style overlay and show it $('#jquery-overlay').css({ width: arrPageSizes[0], height: arrPageSizes[1] }); // Get page scroll var arrPageScroll = ___getPageScroll(); // Calculate top and left offset for the jquery-lightbox div object and show it $('#jquery-lightbox').css({ top: arrPageScroll[1] + (arrPageSizes[3] / 10), left: arrPageScroll[0] }); }); } function _set_timer() { settings.step = settings.step + 1 $("#lightbox-container-image-box-top-middle").reportprogress(settings.step, Math.round(settings.slideShowTimer / 125)); if (settings.step == Math.round(settings.slideShowTimer / 125)) { settings.step = 0; settings.activeImage = settings.activeImage + 1; if (settings.imageArray.length <= settings.activeImage) { settings.activeImage = 0; } $('#lightbox-container-image-box-top-left img').stopTime("timer"); _set_image_to_view(true); } } /** * Prepares image exibition; doing a image´s preloader to calculate it´s size * */ function _set_image_to_view(timer) { // Show the loading $('#lightbox-loading').show(); if (settings.fixedNavigation) { $('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide(); } else { // Hide some elements $('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber,#lightbox-container-image-box-top').hide(); } // Image preload process var objImagePreloader = new Image(); objImagePreloader.onload = function() { $('#lightbox-image').attr('src', settings.imageArray[settings.activeImage][0]); // Perfomance an effect in the image container resizing it _resize_container_image_box(objImagePreloader.width, objImagePreloader.height); // clear onLoad, IE behaves irratically with animated gifs otherwise objImagePreloader.onload = function() { }; }; objImagePreloader.src = settings.imageArray[settings.activeImage][0]; if (timer) { $('#lightbox-container-image-box-top-left img').everyTime(settings.slideShowTimer / Math.round(settings.slideShowTimer / 125), "timer", function(i) { _set_timer(); }, Math.round(settings.slideShowTimer / 125)); } }; /** * Perfomance an effect in the image container resizing it * * @param integer intImageWidth The image´s width that will be showed * @param integer intImageHeight The image´s height that will be showed */ function _resize_container_image_box(intImageWidth, intImageHeight) { // Get current width and height var intCurrentWidth = $('#lightbox-container-image-box').width(); var intCurrentHeight = $('#lightbox-container-image-box').height(); // Get the width and height of the selected image plus the padding var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value // Diferences var intDiffW = intCurrentWidth - intWidth; var intDiffH = intCurrentHeight - intHeight; // Perfomance the effect $('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight }, settings.containerResizeSpeed, function() { _show_image(); }); if ((intDiffW == 0) && (intDiffH == 0)) { if ($.browser.msie) { ___pause(250); } else { ___pause(100); } } $('#lightbox-container-image-data-box').css({ width: intWidth }); $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) - 32 }); }; /** * Show the prepared image * */ function _show_image() { $('#lightbox-loading').hide(); $('#lightbox-image').fadeIn(function() { _show_image_data(); _set_navigation(); }); _preload_neighbor_images(); }; /** * Show the image information * */ function _show_image_data() { $('#lightbox-container-image-data-box').slideDown('fast'); $('#lightbox-image-details-caption').hide(); if (settings.imageArray[settings.activeImage][1]) { $('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show(); } // If we have a image set, display 'Image X of X' if (settings.imageArray.length > 1) { $('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + (settings.activeImage + 1) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show(); } $('#lightbox-container-image-box-top').show(); } /** * Display the button navigations * */ function _set_navigation() { $('#lightbox-nav').show(); // Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just. $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background': 'transparent url(' + settings.imageBlank + ') no-repeat' }); // Show the prev button, if not the first image in set if (settings.activeImage != 0) { if (settings.fixedNavigation) { $('#lightbox-image-details-previous-image, #lightbox-image-details-previous-text').unbind() .bind('click', function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } else { // Show the images button for Next buttons $('#lightbox-image-details-previous-image, #lightbox-image-details-previous-text').unbind().show().bind('click', function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } } else $('#lightbox-image-details-previous-image, #lightbox-image-details-previous-text').hide(); // Show the prev button, if not the first image in set if (settings.activeImage != 0) { if (settings.fixedNavigation) { $('#lightbox-nav-btnPrev').css({ 'background': 'url(' + settings.imageBtnPrev + ') left 50% no-repeat' }) .unbind() .bind('click', function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } else { // Show the images button for Next buttons $('#lightbox-nav-btnPrev').unbind().hover(function() { $(this).css({ 'background': 'url(' + settings.imageBtnPrev + ') left 50% no-repeat' }); }, function() { $(this).css({ 'background': 'transparent url(' + settings.imageBlank + ') no-repeat' }); }).show().bind('click', function() { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); return false; }); } } // Show the next button, if not the last image in set if (settings.activeImage != (settings.imageArray.length - 1)) { if (settings.fixedNavigation) { $('#lightbox-image-details-next-image, #lightbox-image-details-next-text').unbind() .bind('click', function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } else { // Show the images button for Next buttons $('#lightbox-image-details-next-image, #lightbox-image-details-next-text').unbind().show().bind('click', function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } } else $('#lightbox-image-details-next-image, #lightbox-image-details-next-text').hide(); if (settings.activeImage != (settings.imageArray.length - 1)) { if (settings.fixedNavigation) { $('#lightbox-nav-btnNext').css({ 'background': 'url(' + settings.imageBtnNext + ') right 50% no-repeat' }) .unbind() .bind('click', function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } else { // Show the images button for Next buttons $('#lightbox-nav-btnNext').unbind().hover(function() { $(this).css({ 'background': 'url(' + settings.imageBtnNext + ') right 50% no-repeat' }); }, function() { $(this).css({ 'background': 'transparent url(' + settings.imageBlank + ') no-repeat' }); }).show().bind('click', function() { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); return false; }); } } // Enable keyboard navigation _enable_keyboard_navigation(); } /** * Enable a support to keyboard navigation * */ function _enable_keyboard_navigation() { $(document).keydown(function(objEvent) { _keyboard_action(objEvent); }); } /** * Disable the support to keyboard navigation * */ function _disable_keyboard_navigation() { $(document).unbind(); } /** * Perform the keyboard actions * */ function _keyboard_action(objEvent) { // To ie if (objEvent == null) { keycode = event.keyCode; escapeKey = 27; // To Mozilla } else { keycode = objEvent.keyCode; escapeKey = objEvent.DOM_VK_ESCAPE; } // Get the key in lower case form key = String.fromCharCode(keycode).toLowerCase(); // Verify the keys to close the ligthBox if ((key == settings.keyToClose) || (key == 'x') || (keycode == escapeKey)) { _finish(); } // Verify the key to show the previous image if ((key == settings.keyToPrev) || (keycode == 37)) { // If we´re not showing the first image, call the previous if (settings.activeImage != 0) { settings.activeImage = settings.activeImage - 1; _set_image_to_view(); _disable_keyboard_navigation(); } } // Verify the key to show the next image if ((key == settings.keyToNext) || (keycode == 39)) { // If we´re not showing the last image, call the next if (settings.activeImage != (settings.imageArray.length - 1)) { settings.activeImage = settings.activeImage + 1; _set_image_to_view(); _disable_keyboard_navigation(); } } } /** * Preload prev and next images being showed * */ function _preload_neighbor_images() { if ((settings.imageArray.length - 1) > settings.activeImage) { objNext = new Image(); objNext.src = settings.imageArray[settings.activeImage + 1][0]; } if (settings.activeImage > 0) { objPrev = new Image(); objPrev.src = settings.imageArray[settings.activeImage - 1][0]; } } /** * Remove jQuery lightBox plugin HTML markup * */ function _finish() { $('#jquery-lightbox').remove(); $('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); }); // Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay. $('embed, object, select').css({ 'visibility': 'visible' }); } /** / THIRD FUNCTION * getPageSize() by quirksmode.com * * @return Array Return an array with page width, height and window width, height */ function ___getPageSize() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = window.innerWidth + window.scrollMaxX; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { // all except Explorer if (document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else { windowWidth = self.innerWidth; } windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { // other Explorers windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } // for small pages with total height less then height of the viewport if (yScroll < windowHeight) { pageHeight = windowHeight; } else { pageHeight = yScroll; } // for small pages with total width less then width of the viewport if (xScroll < windowWidth) { pageWidth = xScroll; } else { pageWidth = windowWidth; } arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight); return arrayPageSize; }; /** / THIRD FUNCTION * getPageScroll() by quirksmode.com * * @return Array Return an array with x,y page scroll values. */ function ___getPageScroll() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) {// all other Explorers yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } arrayPageScroll = new Array(xScroll, yScroll); return arrayPageScroll; }; /** * Stop the code execution from a escified time in milisecond * */ function ___pause(ms) { var date = new Date(); curDate = null; do { var curDate = new Date(); } while (curDate - date < ms); }; // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once return this.unbind('click').click(_initialize); }; })(jQuery); // Call and execute the function immediately passing the jQuery object /* [===========================================================================] [ JQUERY PROGRESS BAR ] [===========================================================================] */ (function($) { //Main Method $.fn.reportprogress = function(val, maxVal) { var max = 100; if (maxVal) max = maxVal; return this.each( function() { var div = $(this); var innerdiv = div.find(".progress"); if (innerdiv.length != 1) { innerdiv = $("<div class='progress'></div>"); // div.append("<div class='text'>&nbsp;</div>"); // $("<span class='text'>&nbsp;</span>").css("width", div.width()).appendTo(innerdiv); div.append(innerdiv); } var width = Math.round(val / max * 100); innerdiv.css("width", width + "%"); // div.find(".text").html(width + " %"); } ); }; })(jQuery); /* [===========================================================================] [ JQUERY CURVY CORNERS ] [===========================================================================] */ (function($) { $.fn.corner = function(options) { function BlendColour(Col1, Col2, Col1Fraction) { var red1 = parseInt(Col1.substr(1, 2), 16); var green1 = parseInt(Col1.substr(3, 2), 16); var blue1 = parseInt(Col1.substr(5, 2), 16); var red2 = parseInt(Col2.substr(1, 2), 16); var green2 = parseInt(Col2.substr(3, 2), 16); var blue2 = parseInt(Col2.substr(5, 2), 16); if (Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if (endRed > 255) endRed = 255; if (endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if (endGreen > 255) endGreen = 255; if (endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if (endBlue > 255) endBlue = 255; if (endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed) + IntToHex(endGreen) + IntToHex(endBlue); } function IntToHex(strNum) { base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS; } function MakeHex(x) { if ((x >= 0) && (x <= 9)) { return x; } else { switch (x) { case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F"; }; return "F"; }; } function pixelFraction(x, y, r) { var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r, 2) - Math.pow(x, 2))); if ((intersect >= y) && (intersect < (y + 1))) { whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1; }; var intersect = Math.sqrt((Math.pow(r, 2) - Math.pow(y + 1, 2))); if ((intersect >= x) && (intersect < (x + 1))) { whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1; }; var intersect = Math.sqrt((Math.pow(r, 2) - Math.pow(x + 1, 2))); if ((intersect >= y) && (intersect < (y + 1))) { whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1; }; var intersect = Math.sqrt((Math.pow(r, 2) - Math.pow(y, 2))); if ((intersect >= x) && (intersect < (x + 1))) { whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0; }; switch (whatsides) { case "LeftRight": pixelfraction = Math.min(yvalues[0], yvalues[1]) + ((Math.max(yvalues[0], yvalues[1]) - Math.min(yvalues[0], yvalues[1])) / 2); break; case "TopRight": pixelfraction = 1 - (((1 - xvalues[0]) * (1 - yvalues[1])) / 2); break; case "TopBottom": pixelfraction = Math.min(xvalues[0], xvalues[1]) + ((Math.max(xvalues[0], xvalues[1]) - Math.min(xvalues[0], xvalues[1])) / 2); break; case "LeftBottom": pixelfraction = (yvalues[0] * xvalues[1]) / 2; break; default: pixelfraction = 1; }; return pixelfraction; } function rgb2Hex(rgbColour) { try { var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue); } catch (e) { alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex"); }; return hexColour; } function rgb2Array(rgbColour) { var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray; } function format_colour(colour) { var returnColour = "transparent"; if (colour != "" && colour != "transparent") { if (colour.substr(0, 3) == "rgb" && colour.substr(0, 4) != "rgba") { returnColour = rgb2Hex(colour); } else if (colour.length == 4) { returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4); } else { returnColour = colour; }; }; return returnColour; }; function strip_px(value) { return parseInt(((value != "auto" && value.indexOf("%") == -1 && value != "" && value.indexOf("px") !== -1) ? value.slice(0, value.indexOf("px")) : 0)) } function drawPixel(box, intx, inty, colour, transAmount, height, newCorner, image, bgImage, cornerRadius, isBorder, borderWidth, boxWidth, settings) { var $$ = $(box); var pixel = document.createElement("div"); $(pixel).css({ height: height, width: "1px", position: "absolute", "font-size": "1px", overflow: "hidden" }); //var topMaxRadius = Math.max(settings["tr"].radius, settings["tl"].radius); var topMaxRadius = Math.max(settings.tl ? settings.tl.radius : 0, settings.tr ? settings.tr.radius : 0); // Dont apply background image to border pixels if (image == -1 && bgImage != "") { if (topMaxRadius > 0) $(pixel).css("background-position", "-" + ((boxWidth - cornerRadius - borderWidth) + intx) + "px -" + (($$.height() + topMaxRadius - borderWidth) - inty) + "px"); else $(pixel).css("background-position", "-" + ((boxWidth - cornerRadius - borderWidth) + intx) + "px -" + (($$.height()) - inty) + "px"); $(pixel).css({ "background-image": bgImage, "background-repeat": $$.css("background-repeat"), "background-color": colour }); } else { if (!isBorder) $(pixel).css("background-color", colour).addClass('hasBackgroundColor'); else $(pixel).css("background-color", colour); }; if (transAmount != 100) setOpacity(pixel, transAmount); //$(pixel).css('opacity',transAmount/100); $(pixel).css({ top: inty + "px", left: intx + "px" }); return pixel; }; function setOpacity(obj, opacity) { opacity = (opacity == 100) ? 99.999 : opacity; if ($.browser.safari && obj.tagName != "IFRAME") { // Get array of RGB values var rgbArray = rgb2Array(obj.style.backgroundColor); // Get RGB values var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); // Safari using RGBA support obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity / 100 + ")"; } else if (typeof (obj.style.opacity) != "undefined") { // W3C obj.style.opacity = opacity / 100; } else if (typeof (obj.style.MozOpacity) != "undefined") { // Older Mozilla obj.style.MozOpacity = opacity / 100; } else if (typeof (obj.style.filter) != "undefined") { // IE obj.style.filter = "alpha(opacity:" + opacity + ")"; } else if (typeof (obj.style.KHTMLOpacity) != "undefined") { // Older KHTML Based Browsers obj.style.KHTMLOpacity = opacity / 100; } } // Apply the corners function applyCorners(box, settings) { var $$ = $(box); // Get CSS of box and define vars var thebgImage = $$.css("backgroundImage"); var topContainer = null; var bottomContainer = null; var masterCorners = new Array(); var contentDIV = null; var boxHeight = strip_px($$.css("height")) ? strip_px($$.css("height")) : box.scrollHeight; var boxWidth = strip_px($$.css("width")) ? strip_px($$.css("width")) : box.scrollWidth; var borderWidth = strip_px($$.css("borderTopWidth")) ? strip_px($$.css("borderTopWidth")) : 0; var boxPaddingTop = strip_px($$.css("paddingTop")); var boxPaddingBottom = strip_px($$.css("paddingBottom")); var boxPaddingLeft = strip_px($$.css("paddingLeft")); var boxPaddingRight = strip_px($$.css("paddingRight")); var boxColour = format_colour($$.css("backgroundColor")); var bgImage = (thebgImage != "none" && thebgImage != "initial") ? thebgImage : ""; //var boxContent = $$.html(); var borderColour = format_colour($$.css("borderTopColor")); var borderString = borderWidth + "px" + " solid " + borderColour; var topMaxRadius = Math.max(settings.tl ? settings.tl.radius : 0, settings.tr ? settings.tr.radius : 0); var botMaxRadius = Math.max(settings.bl ? settings.bl.radius : 0, settings.br ? settings.br.radius : 0); $$.addClass('hasCorners').css({ "padding": "0", "borderColor": box.style.borderColour, 'overflow': 'visible' }); if (box.style.position != "absolute") $$.css("position", "relative"); if (($.browser.msie)) { if ($.browser.version == 6 && box.style.width == "auto" && box.style.height == "auto") $$.css("width", "100%"); $$.css("zoom", "1"); $("*", $$).css("zoom", "normal"); } for (var t = 0; t < 2; t++) { switch (t) { case 0: if (settings.tl || settings.tr) { var newMainContainer = document.createElement("div"); topContainer = box.appendChild(newMainContainer); $(topContainer).css({ width: "100%", "font-size": "1px", overflow: "hidden", position: "absolute", "padding-left": borderWidth, "padding-right": borderWidth, height: topMaxRadius + "px", top: 0 - topMaxRadius + "px", left: 0 - borderWidth + "px" }).addClass('topContainer'); }; break; case 1: if (settings.bl || settings.br) { var newMainContainer = document.createElement("div"); bottomContainer = box.appendChild(newMainContainer); $(bottomContainer).css({ width: "100%", "font-size": "1px", overflow: "hidden", position: "absolute", "padding-left": borderWidth, "padding-right": borderWidth, height: botMaxRadius, bottom: 0 - botMaxRadius + "px", left: 0 - borderWidth + "px" }).addClass('bottomContainer'); }; break; }; }; if (settings.autoPad == true) { //$$.html(""); var contentContainer = document.createElement("div"); var contentContainer2 = document.createElement("div"); var clearDiv = document.createElement("div"); $(contentContainer2).css({ margin: "0", "padding-bottom": boxPaddingBottom, "padding-top": boxPaddingTop, "padding-left": boxPaddingLeft, "padding-right": boxPaddingRight, 'overflow': 'visible', height: "100%" }).addClass('hasBackgroundColor content_container'); $(contentContainer).css({ position: "relative", 'float': "left", width: "100%", "margin-top": "-" + Math.abs(topMaxRadius - borderWidth) + "px", "margin-bottom": "-" + Math.abs(botMaxRadius - borderWidth) + "px", height: "100%" }).addClass = "autoPadDiv"; $(clearDiv).css("clear", "both"); contentContainer2.appendChild(contentContainer); contentContainer2.appendChild(clearDiv); $$.wrapInner(contentContainer2); }; if (topContainer) $$.css("border-top", 0); if (bottomContainer) $$.css("border-bottom", 0); var corners = ["tr", "tl", "br", "bl"]; for (var i in corners) { if (i > -1 < 4) { var cc = corners[i]; if (!settings[cc]) { if (((cc == "tr" || cc == "tl") && topContainer != null) || ((cc == "br" || cc == "bl") && bottomContainer != null)) { var newCorner = document.createElement("div"); $(newCorner).css({ position: "relative", "font-size": "1px", overflow: "hidden" }); if (bgImage == "") $(newCorner).css("background-color", boxColour); else $(newCorner).css("background-image", bgImage).css("background-color", boxColour); ; switch (cc) { case "tl": $(newCorner).css({ height: topMaxRadius - borderWidth, "margin-right": settings.tr.radius - (borderWidth * 2), "border-left": borderString, "border-top": borderString, left: -borderWidth + "px", "background-repeat": $$.css("background-repeat"), "background-position": borderWidth + "px 0px" }); break; case "tr": $(newCorner).css({ height: topMaxRadius - borderWidth, "margin-left": settings.tl.radius - (borderWidth * 2), "border-right": borderString, "border-top": borderString, left: borderWidth + "px", "background-repeat": $$.css("background-repeat"), "background-position": "-" + (topMaxRadius + borderWidth) + "px 0px" }); break; case "bl": if (topMaxRadius > 0) $(newCorner).css({ height: botMaxRadius - borderWidth, "margin-right": settings.br.radius - (borderWidth * 2), "border-left": borderString, "border-bottom": borderString, left: -borderWidth + "px", "background-repeat": $$.css("background-repeat"), "background-position": "0px -" + ($$.height() + topMaxRadius - borderWidth + 1) + "px" }); else $(newCorner).css({ height: botMaxRadius - borderWidth, "margin-right": settings.br.radius - (borderWidth * 2), "border-left": borderString, "border-bottom": borderString, left: -borderWidth + "px", "background-repeat": $$.css("background-repeat"), "background-position": "0px -" + ($$.height()) + "px" }); break; case "br": if (topMaxRadius > 0) $(newCorner).css({ height: botMaxRadius - borderWidth, "margin-left": settings.bl.radius - (borderWidth * 2), "border-right": borderString, "border-bottom": borderString, left: borderWidth + "px", "background-repeat": $$.css("background-repeat"), "background-position": "-" + settings.bl.radius + borderWidth + "px -" + ($$.height() + topMaxRadius - borderWidth + 1) + "px" }); else $(newCorner).css({ height: botMaxRadius - borderWidth, "margin-left": settings.bl.radius - (borderWidth * 2), "border-right": borderString, "border-bottom": borderString, left: borderWidth + "px", "background-repeat": $$.css("background-repeat"), "background-position": "-" + settings.bl.radius + borderWidth + "px -" + ($$.height()) + "px" }); break; }; }; } else { if (masterCorners[settings[cc].radius]) { var newCorner = masterCorners[settings[cc].radius].cloneNode(true); } else { var newCorner = document.createElement("DIV"); $(newCorner).css({ height: settings[cc].radius, width: settings[cc].radius, position: "absolute", "font-size": "1px", overflow: "hidden" }); var borderRadius = parseInt(settings[cc].radius - borderWidth); for (var intx = 0, j = settings[cc].radius; intx < j; intx++) { if ((intx + 1) >= borderRadius) var y1 = -1; else var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx + 1), 2))) - 1); if (borderRadius != j) { if ((intx) >= borderRadius) var y2 = -1; else var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow(intx, 2))); if ((intx + 1) >= j) var y3 = -1; else var y3 = (Math.floor(Math.sqrt(Math.pow(j, 2) - Math.pow((intx + 1), 2))) - 1); }; if ((intx) >= j) var y4 = -1; else var y4 = Math.ceil(Math.sqrt(Math.pow(j, 2) - Math.pow(intx, 2))); if (y1 > -1) newCorner.appendChild(drawPixel(box, intx, 0, boxColour, 100, (y1 + 1), newCorner, -1, bgImage, settings[cc].radius, 0, borderWidth, boxWidth, settings)); if (borderRadius != j) { for (var inty = (y1 + 1); inty < y2; inty++) { if (settings.antiAlias) { if (bgImage != "") { var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if (borderFract < 30) { newCorner.appendChild(drawPixel(box, intx, inty, borderColour, 100, 1, newCorner, 0, bgImage, settings[cc].radius, 1, borderWidth, boxWidth, settings)); } else { newCorner.appendChild(drawPixel(box, intx, inty, borderColour, 100, 1, newCorner, -1, bgImage, settings[cc].radius, 1, borderWidth, boxWidth, settings)); }; } else { var pixelcolour = BlendColour(boxColour, borderColour, pixelFraction(intx, inty, borderRadius)); newCorner.appendChild(drawPixel(box, intx, inty, pixelcolour, 100, 1, newCorner, 0, bgImage, settings[cc].radius, cc, 1, borderWidth, boxWidth, settings)); }; }; }; if (settings.antiAlias) { if (y3 >= y2) { if (y2 == -1) y2 = 0; newCorner.appendChild(drawPixel(box, intx, y2, borderColour, 100, (y3 - y2 + 1), newCorner, 0, bgImage, 0, 1, borderWidth, boxWidth, settings)); } } else { if (y3 >= y1) { newCorner.appendChild(drawPixel(box, intx, (y1 + 1), borderColour, 100, (y3 - y1), newCorner, 0, bgImage, 0, 1, borderWidth, boxWidth, settings)); } }; var outsideColour = borderColour; } else { var outsideColour = boxColour; var y3 = y1; }; if (settings.antiAlias) { for (var inty = (y3 + 1); inty < y4; inty++) { newCorner.appendChild(drawPixel(box, intx, inty, outsideColour, (pixelFraction(intx, inty, j) * 100), 1, newCorner, ((borderWidth > 0) ? 0 : -1), bgImage, settings[cc].radius, 1, borderWidth, boxWidth, settings)); }; }; }; masterCorners[settings[cc].radius] = newCorner.cloneNode(true); }; if (cc != "br") { for (var t = 0, k = newCorner.childNodes.length; t < k; t++) { var pixelBar = newCorner.childNodes[t]; var pixelBarTop = strip_px($(pixelBar).css("top")); var pixelBarLeft = strip_px($(pixelBar).css("left")); var pixelBarHeight = strip_px($(pixelBar).css("height")); if (cc == "tl" || cc == "bl") { $(pixelBar).css("left", settings[cc].radius - pixelBarLeft - 1 + "px"); }; if (cc == "tr" || cc == "tl") { $(pixelBar).css("top", settings[cc].radius - pixelBarHeight - pixelBarTop + "px"); }; switch (cc) { case "tr": $(pixelBar).css("background-position", "-" + Math.abs((boxWidth - settings[cc].radius + borderWidth) + pixelBarLeft) + "px -" + Math.abs(settings[cc].radius - pixelBarHeight - pixelBarTop - borderWidth) + "px"); break; case "tl": $(pixelBar).css("background-position", "-" + Math.abs((settings[cc].radius - pixelBarLeft - 1) - borderWidth) + "px -" + Math.abs(settings[cc].radius - pixelBarHeight - pixelBarTop - borderWidth) + "px"); break; case "bl": if (topMaxRadius > 0) $(pixelBar).css("background-position", "-" + Math.abs((settings[cc].radius - pixelBarLeft - 1) - borderWidth) + "px -" + Math.abs(($$.height() + topMaxRadius - borderWidth + 1)) + "px"); else $(pixelBar).css("background-position", "-" + Math.abs((settings[cc].radius - pixelBarLeft - 1) - borderWidth) + "px -" + Math.abs(($$.height())) + "px"); break; }; }; }; }; if (newCorner) { switch (cc) { case "tl": if ($(newCorner).css("position") == "absolute") $(newCorner).css("top", "0"); if ($(newCorner).css("position") == "absolute") $(newCorner).css("left", "0"); if (topContainer) topContainer.appendChild(newCorner); break; case "tr": if ($(newCorner).css("position") == "absolute") $(newCorner).css("top", "0"); if ($(newCorner).css("position") == "absolute") $(newCorner).css("right", "0"); if (topContainer) topContainer.appendChild(newCorner); break; case "bl": if ($(newCorner).css("position") == "absolute") $(newCorner).css("bottom", "0"); if (newCorner.style.position == "absolute") $(newCorner).css("left", "0"); if (bottomContainer) bottomContainer.appendChild(newCorner); break; case "br": if ($(newCorner).css("position") == "absolute") $(newCorner).css("bottom", "0"); if ($(newCorner).css("position") == "absolute") $(newCorner).css("right", "0"); if (bottomContainer) bottomContainer.appendChild(newCorner); break; }; }; }; }; var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(settings.tl.radius - settings.tr.radius); radiusDiff["b"] = Math.abs(settings.bl.radius - settings.br.radius); for (z in radiusDiff) { if (z == "t" || z == "b") { if (radiusDiff[z]) { var smallerCornerType = ((settings[z + "l"].radius < settings[z + "r"].radius) ? z + "l" : z + "r"); var newFiller = document.createElement("div"); $(newFiller).css({ height: radiusDiff[z], width: settings[smallerCornerType].radius + "px", position: "absolute", "font-size": "1px", overflow: "hidden", "background-color": boxColour, "background-image": bgImage }); switch (smallerCornerType) { case "tl": $(newFiller).css({ "bottom": "0", "left": "0", "border-left": borderString, "background-position": "0px -" + (settings[smallerCornerType].radius - borderWidth) }); topContainer.appendChild(newFiller); break; case "tr": $(newFiller).css({ "bottom": "0", "right": "0", "border-right": borderString, "background-position": "0px -" + (settings[smallerCornerType].radius - borderWidth) + "px" }); topContainer.appendChild(newFiller); break; case "bl": $(newFiller).css({ "top": "0", "left": "0", "border-left": borderString, "background-position": "0px -" + ($$.height() + settings[smallerCornerType].radius - borderWidth) }); bottomContainer.appendChild(newFiller); break; case "br": $(newFiller).css({ "top": "0", "right": "0", "border-right": borderString, "background-position": "0px -" + ($$.height() + settings[smallerCornerType].radius - borderWidth) }); bottomContainer.appendChild(newFiller); break; } }; var newFillerBar = document.createElement("div"); $(newFillerBar).css({ position: "relative", "font-size": "1px", overflow: "hidden", "background-color": boxColour, "background-image": bgImage, "background-repeat": $$.css("background-repeat") }); switch (z) { case "t": if (topContainer) { if (settings.tl.radius && settings.tr.radius) { $(newFillerBar).css({ height: topMaxRadius - borderWidth + "px", "margin-left": settings.tl.radius - borderWidth + "px", "margin-right": settings.tr.radius - borderWidth + "px", "border-top": borderString }).addClass('hasBackgroundColor'); if (bgImage != "") $(newFillerBar).css("background-position", "-" + (topMaxRadius + borderWidth) + "px 0px"); topContainer.appendChild(newFillerBar); }; $$.css("background-position", "0px -" + (topMaxRadius - borderWidth + 1) + "px"); }; break; case "b": if (bottomContainer) { if (settings.bl.radius && settings.br.radius) { $(newFillerBar).css({ height: botMaxRadius - borderWidth + "px", "margin-left": settings.bl.radius - borderWidth + "px", "margin-right": settings.br.radius - borderWidth + "px", "border-bottom": borderString }); if (bgImage != "" && topMaxRadius > 0) $(newFillerBar).css("background-position", "-" + (settings.bl.radius - borderWidth) + "px -" + ($$.height() + topMaxRadius - borderWidth + 1) + "px"); else $(newFillerBar).css("background-position", "-" + (settings.bl.radius - borderWidth) + "px -" + ($$.height()) + "px").addClass('hasBackgroundColor'); bottomContainer.appendChild(newFillerBar); }; }; break; }; }; }; $$.prepend(topContainer); $$.prepend(bottomContainer); } var settings = { tl: { radius: 8 }, tr: { radius: 8 }, bl: { radius: 8 }, br: { radius: 8 }, antiAlias: true, autoPad: true, validTags: ["div"] }; if (options && typeof (options) != 'string') $.extend(settings, options); return this.each(function() { if (!$(this).is('.hasCorners')) { applyCorners(this, settings); } }); }; })(jQuery); /* [===========================================================================] [ JQUERY TIMER ] [===========================================================================] */ jQuery.fn.extend({ everyTime: function(interval, label, fn, times, belay) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, times, belay); }); }, oneTime: function(interval, label, fn) { return this.each(function() { jQuery.timer.add(this, interval, label, fn, 1); }); }, stopTime: function(label, fn) { return this.each(function() { jQuery.timer.remove(this, label, fn); }); } }); jQuery.event.special jQuery.extend({ timer: { global: [], guid: 1, dataKey: "jQuery.timer", regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/, powers: { // Yeah this is major overkill... 'ms': 1, 'cs': 10, 'ds': 100, 's': 1000, 'das': 10000, 'hs': 100000, 'ks': 1000000 }, timeParse: function(value) { if (value == undefined || value == null) return null; var result = this.regex.exec(jQuery.trim(value.toString())); if (result[2]) { var num = parseFloat(result[1]); var mult = this.powers[result[2]] || 1; return num * mult; } else { return value; } }, add: function(element, interval, label, fn, times, belay) { var counter = 0; if (jQuery.isFunction(label)) { if (!times) times = fn; fn = label; label = interval; } interval = jQuery.timer.timeParse(interval); if (typeof interval != 'number' || isNaN(interval) || interval <= 0) return; if (times && times.constructor != Number) { belay = !!times; times = 0; } times = times || 0; belay = belay || false; var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {}); if (!timers[label]) timers[label] = {}; fn.timerID = fn.timerID || this.guid++; var handler = function() { if (belay && this.inProgress) return; this.inProgress = true; if ((++counter > times && times !== 0) || fn.call(element, counter) === false) jQuery.timer.remove(element, label, fn); this.inProgress = false; }; handler.timerID = fn.timerID; if (!timers[label][fn.timerID]) timers[label][fn.timerID] = window.setInterval(handler, interval); this.global.push(element); }, remove: function(element, label, fn) { var timers = jQuery.data(element, this.dataKey), ret; if (timers) { if (!label) { for (label in timers) this.remove(element, label, fn); } else if (timers[label]) { if (fn) { if (fn.timerID) { window.clearInterval(timers[label][fn.timerID]); delete timers[label][fn.timerID]; } } else { for (var fn in timers[label]) { window.clearInterval(timers[label][fn]); delete timers[label][fn]; } } for (ret in timers[label]) break; if (!ret) { ret = null; delete timers[label]; } } for (ret in timers) break; if (!ret) jQuery.removeData(element, this.dataKey); } } } }); jQuery(window).bind("unload", function() { jQuery.each(jQuery.timer.global, function(index, item) { jQuery.timer.remove(item); }); });
JavaScript
$().ready(function () { var dates = $("#StartDateTime,#EndDateTime").datepicker({ dateFormat: 'yy年mm月dd日', numberOfMonths: 3, onSelect: function (selectedDate) { var option = this.id == "StartDateTime" ? "minDate" : "maxDate", instance = $(this).data("datepicker"), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings); dates.not(this).datepicker("option", option, date); if (this.id == "StartDateTime") $("#EndDateTime").datepicker("show"); } }); });
JavaScript
$().ready(function () { var dates = $("#StartDateTime,#EndDateTime").datepicker({ dateFormat: 'yy年mm月dd日', numberOfMonths: 3, onSelect: function (selectedDate) { var option = this.id == "StartDateTime" ? "minDate" : "maxDate", instance = $(this).data("datepicker"), date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings); dates.not(this).datepicker("option", option, date); if (this.id == "StartDateTime") $("#EndDateTime").datepicker("show"); } }); });
JavaScript
$().ready(function () { $("form").submit(function () { if ($(".input-validation-error").length == 0) { $(".btn-container input").css("disable", "disable"); $(".btn-container input").val("Uploading……"); } }); });
JavaScript